2014-01-16 60 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)); 
    } 
相关问题