2013-06-20 118 views
7

如何获得TextView的背景颜色?如何获取TextView的背景颜色?

当我按下TextView时,我想根据使用中的背景颜色更改背景颜色。

TextView中没有一个方法,如:

getBackgroundResource() 

编辑: 我宁愿让背景色的渣油。

+0

或者我通过互联网寻找一点点,但它似乎没有办法从xml定义的颜色得到这样的id。可能你应该改变你的应用程序并以编程方式管理背景颜色,也许在onClick事件中保留一些颜色变化。 – Rob013

回答

13

如果你想获得背景的颜色代码试试这个:

if (textView.getBackground() instanceof ColorDrawable) { 
    ColorDrawable cd = (ColorDrawable) textView.getBackground(); 
    int colorCode = cd.getColor(); 
} 
+0

我编辑我的问题:我如何从这种颜色的resId? – OrSmolnik

+0

好吧,我现在编辑答案 –

+0

我试过这个,但在你的回答中的第一行之后,我得到cd是空的 – OrSmolnik

0

答:

我们不能使用consts像color.red或color.white。

我们需要弄清楚它的

int intID = (ColorDrawable) holder.tvChoose.getBackground().getColor(); 

如何代表它和我们有颜色的假身份证

0

ColorDrawable.getColor()将只与上述11 API级别上工作,所以你可以使用此代码从开始就支持它。 我使用以下API级别反射11

public static int getBackgroundColor(TextView textView) { 
     Drawable drawable = textView.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; 
    } 
0

如果您正在使用AppCompat使用这样的:

ViewCompat.getBackgroundTintList(textView).getDefaultColor(); 

旁注:要小心,如果你投以ColorDrawable,因为它可以抛出一个ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable