我有一个以可绘制为背景的 TextView。使用 StateListDrawable 对象,我尝试以编程方式设置背景颜色,但遇到了意想不到的行为:我在一个对象中设置了颜色,而在另一个对象中它发生了变化。这应该是不可能的。
相关代码:
GradientDrawable notPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
GradientDrawable isPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
isPressed.setColor(util.getColour(api, this));
StateListDrawable bg = new StateListDrawable();
// bg.addState(new int[] { android.R.attr.state_pressed }, isPressed);
bg.addState(StateSet.WILD_CARD, notPressed);
textView.setBackgroundDrawable(bg);
可绘制对象:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1dp" android:color="@color/divider" />
<solid android:color="@color/background_button" />
</shape>
util.getColour
根据 api 的值返回颜色资源。
奇怪的是在上面的代码中isPressed
设置了drawable的颜色,但是之后这个drawable就没有使用了。相反,只有notPressed
可绘制对象被添加到 textView 的背景中。
但是textView的背景颜色变成了isPressed
drawable的颜色!这应该是不可能的,因为它们应该是两个不同的对象,即使它们是从同一个可绘制资源创建的。