2014-02-15 5 views

답변

5

이 시도 ...

public static int getBackgroundColor(TextView textView) { 
    ColorDrawable drawable = (ColorDrawable) textView.getBackground(); 
    if (Build.VERSION.SDK_INT >= 11) { 
     return drawable.getColor(); 
    } 
    try { 
     Field field = drawable.getClass().getDeclaredField("mState"); 
     field.setAccessible(true); 
     Object object = field.get(drawable); 
     field = object.getClass().getDeclaredField("mUseColor"); 
     field.setAccessible(true); 
     return field.getInt(object); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 
    return 0; 
} 
+0

고마워요. @SuppressLint ("NewApi")를 methode에 추가해야만 API 9를 사용하고 있습니다. –

+0

API> 21에서 실패합니다. – EmmanuelMess

3

멋진 대답을 사용! 를 들어

  • mUseColor
  • mBaseColor

위의 코드는 설정하려면 큰하지만 색상을 받고 : 난 그냥 private 필드 mState는 두 가지 색상 필드를 가지고 추가하고 싶었 색상의 경우 StateListDrawable 인스턴스의 문제로 인해 두 필드를 모두 설정해야합니다.

final int color = Color.RED; 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
     drawable.setColor(color); 
    } else { 
     try { 
      final Field stateField = drawable.getClass().getDeclaredField(
        "mState"); 
      stateField.setAccessible(true); 
      final Object state = stateField.get(drawable); 

      final Field useColorField = state.getClass().getDeclaredField(
        "mUseColor"); 
      useColorField.setAccessible(true); 
      useColorField.setInt(state, color); 

      final Field baseColorField = state.getClass().getDeclaredField(
        "mBaseColor"); 
      baseColorField.setAccessible(true); 
      baseColorField.setInt(state, color); 
     } catch (Exception e) { 
      Log.e(LOG_TAG, "Cannot set color to the drawable!"); 
     } 
    } 

희망이있었습니다. :)

관련 문제