我有一個帶有可繪製背景的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
drawable被添加到textView的背景。
但textView的背景顏色變成了isPressed
可繪製的顏色!這應該是不可能的,因爲它們應該是兩個不同的對象,即使它們是從相同的可繪製資源創建的。
檢查:
您可以使用此代碼來解決這個問題。 – 2013-03-20 17:20:35