I have a Textview called myText defined in xml. The textview has an accompanying drawable which is actually a selector.
When the user clicks on the TextView I want to not only change the drawable, but also the color of the text. My code for effecting the change is below. The problem is only the drawable is changing. The text is not changing. How do I fix this code so the text color changes as well?
Inside activity
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));
}
selector
<?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>
I found the problem. I was comparing apples and oranges. The fix is to add getResources().getColor
to the if clause.
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));
}
You can use the Color
class, for instance: Color.RED
. Or if you have a HTML style color, you can even use: .setTextColor(Color.parseColor("#FFFFFF"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.