2013-02-08 3 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'은 API 1 이후에 사용 가능하고, view.getBackground()도 가능합니다. –

+0

Nevermind. 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

으로 레이아웃의 배경색을 얻으십시오 :

RelativeLayout 인 경우 ID를 찾고 LinearLayout 대신 객체를 사용하십시오

0

이 작업을 수행하는 가장 간단한 방법은 다음과 같습니다

view.getSolidColor(); 
0

짧고 간단한 방법 : 배경 색상을 변경 될 수 있으므로

int color = ((ColorDrawable)view.getBackground()).getColor();