How to define ColorStateList for TextView?

2019-01-21 05:19发布

When my ListViewItem is highlighted, I want the text to turn white. How can I define this?

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:color="@color/testcolor1"/>
   <item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
   <item android:state_enabled="false" android:color="@color/testcolor3" />
   <item android:color="@color/testcolor5"/>
 </selector>

2条回答
孤傲高冷的网名
2楼-- · 2019-01-21 05:27

Create file res/drawable/text_color.xml:

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" />
    <item android:state_focused="true" android:state_pressed="true" android:color="#ffffff" />
    <item android:state_focused="false" android:state_pressed="true" android:color="#ffffff" />
    <item android:color="#000000" />
</selector>

Then use @drawable/text_color from xml (or R.drawable.text_color from code) as text color for your list view items.

查看更多
Fickle 薄情
3楼-- · 2019-01-21 05:39

In addition to what others have stated above, I would like to highlight one point, taken from the below url.

https://developer.android.com/reference/android/content/res/ColorStateList.html

Note: The list of state specs will be matched against in the order that they appear in the XML file. For this reason, more-specific items should be placed earlier in the file. An item with no state spec is considered to match any set of states and is generally useful as a final item to be used as a default.

It's important that you have the broader condition towards the bottom in the selector tag. Hope this helps!

查看更多
登录 后发表回答