2014-02-15 49 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」),現在只使用API​​ 9 –

+0

在API> 21上失敗 – EmmanuelMess

3

偉大的答案!我只是想補充的是,私有字段mState具有雙色場:

  • mUseColor
  • mBaseColor

對於越來越顏色上面的代碼是偉大的,但如果你想的顏色,由於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!"); 
     } 
    } 

希望這有幫助! :)