2014-01-16 62 views
0

我有一個在xml中定義的名爲myText的Textview。 textview有一個實際上是選擇器的伴隨drawable。如何在TextView中更改文本的顏色

當用戶單擊TextView時,我不僅要更改drawable,還要更改文本的顏色。我的代碼用於實現更改如下。問題只是可繪製的變化。文字沒有改變。我如何修復這段代碼,以便文本顏色也發生變化?

內活動

if (R.color.my_red == myText.getCurrentTextColor()) { 
     myText.setSelected(true); 
     myText.setTextColor(getResources().getColor(R.color.my_blue)); 
    } else { 
     myText.setSelected(false); 
     myText.setTextColor(getResources().getColor(R.color.my_red)); 
    } 

選擇

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@drawable/im_red" android:state_pressed="true"/> 
    <item android:drawable="@drawable/im_blue"/> 

</selector> 

回答

0

可以使用Color類,例如:Color.RED。或者如果你有HTML風格的顏色,你甚至可以使用:.setTextColor(Color.parseColor("#FFFFFF"))

+0

這基本上和user3093402已經做的一樣。 user3093402只是傳遞一個顏色資源。 –

+0

感謝張貼,但我找到了解決方案。看到我上面的迴應。 – user3093402

1

我發現了這個問題。我正在比較蘋果和橘子。修正是將getResources().getColor添加到if子句中。

if (getResources().getColor(R.color.my_red) == myText.getCurrentTextColor()) { 
     myText.setSelected(true); 
     myText.setTextColor(getResources().getColor(R.color.my_blue)); 
    } else { 
     myText.setSelected(false); 
     myText.setTextColor(getResources().getColor(R.color.my_red)); 
    } 
相關問題