【发布时间】:2013-03-20 17:13:54
【问题描述】:
我有一个以可绘制为背景的 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的值返回颜色资源。
奇怪的是,在上面的代码中,isPresseddrawable 的颜色被设置了,但是之后这个 drawable 就没有被使用了。相反,只有notPressed drawable 被添加到 textView 的背景中。
但是textView的背景颜色变成了isPresseddrawable的颜色!这应该是不可能的,因为它们应该是两个不同的对象,即使它们是从同一个可绘制资源创建的。
【问题讨论】:
-
检查
notPressed!=isPressed是否是同一个对象。
标签: java android android-resources android-drawable