Android 是否有这样的方法调用;getBackgroundColor";?
TextView中是否有这样的方法调用“getBackgroundColor”? 如果我有两个文本视图:tv1和tv2在一个线性布局中。我做了什么:tv1.setBackgroundColor(Color.BLUE)Android 是否有这样的方法调用;getBackgroundColor";?,android,textview,Android,Textview,TextView中是否有这样的方法调用“getBackgroundColor”? 如果我有两个文本视图:tv1和tv2在一个线性布局中。我做了什么:tv1.setBackgroundColor(Color.BLUE) 现在如果我想让tv2的背景色和tv1一样,我怎么才能先得到tv1的背景色,然后再得到tv2的背景色呢?没有这样的方法,因为现在普遍存在“背景色”——可以有任何可绘制的对象(例如图片)。所以,你应该记住你为文本设置了什么颜色 如果无法保存,请使用View.setTag()和View.
现在如果我想让tv2的背景色和tv1一样,我怎么才能先得到tv1的背景色,然后再得到tv2的背景色呢?没有这样的方法,因为现在普遍存在“背景色”——可以有任何
可绘制的对象(例如图片)。所以,你应该记住你为文本设置了什么颜色
如果无法保存,请使用View.setTag()
和View.getTag()
方法存储与视图关联的任何值。您将在此处找到解决方案:
它将是这样的:
((PaintDrawable) tv.getBackground()).getPaint()
设置背景颜色将以指定的颜色作为背景设置可绘制图形,即以下示例将很好地工作:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout_name);
TextView t1 = (TextView) findViewById(R.id.text1);
TextView t2 = (TextView) findViewById(R.id.text2);
t1.setBackgroundColor(Color.GREEN);
t2.setBackgroundDrawable(t1.getBackground());
}
有一个比波旁威士忌更好的解决方案:
((ColorDrawable)view.getBackground()).getColor();
优点是我们得到了一个整数,它可以与color类给出的颜色枚举相比较。这对我很有用
public static int getColor(View v) {
if(Build.VERSION.SDK_INT>=11)
{
return ((ColorDrawable)v.getBackground()).getColor();
}
else
{
try
{
Field f=View.class.getDeclaredField("mState");
f.setAccessible(true);
Object mState=f.get(v);
Field f2=mState.getClass().getDeclaredField("mUseColor");
f2.setAccessible(true);
return (int) f2.get(mState);
}
catch (Exception e)
{
}
}
return 0;
}
但事实上,如果你想复制可绘制视图,没有问题,颜色就是可绘制的,所以复制Jens提到的可绘制视图。如果所讨论的视图是文本视图,这可能会起作用,但如果它是一般视图,它将抛出一个ClassCastException
:android.graphics.drawable.NinePatchDrawable.@Bourbon我如何比较它?我想比较TextView背景色和白色之类的颜色。我该怎么做呢?嘿,如果你使用我在这里提供的另一个解决方案(见下文),这很简单。这是迄今为止最优雅的解决方案。这应该是公认的答案+1.现在它说,setBackgroundDrawable()已被弃用。还有其他选择吗?答案很简单,但对我来说很不幸:ColorDrawable.getColor()在API级别11之前不可用。