2013-03-20 95 views
0

我有一個帶有可繪製背景的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可繪製的顏色!這應該是不可能的,因爲它們應該是兩個不同的對象,即使它們是從相同的可繪製資源創建的。

+0

檢查:

您可以使用此代碼來解決這個問題。 – 2013-03-20 17:20:35

回答

0

Android爲可繪製資源使用相同的對象,除非您指定需要它的新副本。 !如果`notPressed = isPressed`我懷疑兩者是相同的對象

Drawable isPressed = notPressed.getConstantState().newDrawable(); 
相關問題