2013-02-08 53 views
30

自分のコードからレイアウトの背景色を探したいと思います。それを見つける方法はありますか? linearLayout.getBackgroundColor()のようなもの?レイアウトの背景色を取得する

+0

背景は色ではないかもしれないので、あなたはlinearLayout.getBackgroundを(使用できる)を得れますあなたは 'Drawable'です。特に背景色を取得するAPIはありません。 [Viewのドキュメントをもっと読む](http://developer.android.com/reference/android/view/View.html#getBackground%28%29) –

+0

しかし、私は本当にレイアウトの色を見つける必要があります。別の方法があるはずです!またはDrawableから取得することは可能ですか? –

答えて

75

これは、背景が単色である場合にのみAPI 11以降で達成できます。

  int color = Color.TRANSPARENT; 
      Drawable background = view.getBackground(); 
      if (background instanceof ColorDrawable) 
       color = ((ColorDrawable) background).getColor(); 
+0

私はちょうど私の答えを編集し、具体的にはうまくいくと言いました!しかし、なぜAPI 11以上の制限があるのか​​わかりません。 'ColorDrawable'はAPI1とview.getBackground()から利用できるようです。 –

+0

心配しないでください。私はColorDrawableの '.getColor'がAPI 11で追加されたことを知ります。 –

+0

' Drawable'を 'Bitmap'に変換して最初のピクセルを得ることができます。 'int color = bitmap.getPixel(0、0);' –

10

ColorDrawable.getColorは()だけで11以上のAPIレベルで動作しますので、あなたは、APIレベルからAPIレベル以下の1.の反射を、それをサポートするために、このコードを使用することができます11.

public static int getBackgroundColor(View view) { 
     Drawable drawable = view.getBackground(); 
     if (drawable instanceof ColorDrawable) { 
      ColorDrawable colorDrawable = (ColorDrawable) drawable; 
      if (Build.VERSION.SDK_INT >= 11) { 
       return colorDrawable.getColor(); 
      } 
      try { 
       Field field = colorDrawable.getClass().getDeclaredField("mState"); 
       field.setAccessible(true); 
       Object object = field.get(colorDrawable); 
       field = object.getClass().getDeclaredField("mUseColor"); 
       field.setAccessible(true); 
       return field.getInt(object); 
      } catch (NoSuchFieldException e) { 
       e.printStackTrace(); 
      } catch (IllegalAccessException e) { 
       e.printStackTrace(); 
      } 
     } 
     return 0; 
    } 
8

へレイアウトの背景色を取得する:

LinearLayout lay = (LinearLayout) findViewById(R.id.lay1); 
ColorDrawable viewColor = (ColorDrawable) lay.getBackground(); 
int colorId = viewColor.getColor(); 

RelativeLayoutの場合、そのIDを見つけ、LinearLayoutの代わりにオブジェクトを使用します。

0

これを実行する最も簡単な方法は次のとおりです。

view.getSolidColor(); 
0

ショートとシンプルな方法:

int color = ((ColorDrawable)view.getBackground()).getColor(); 
関連する問題