How to define ColorStateList for TextView?

微笑、不失礼 提交于 2019-11-28 16:06:20
Konstantin Burov

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.

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!

Try this...

First, create a color state list text_color.xml placed in res/color directory.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="MissingDefaultResource">
  <item android:color="#000000" android:state_enabled="false"/>
  <item android:color="#FFFFFF"/>
</selector>

Second, use

getColorStateList(@NonNull Context context,
            @ColorRes int id)

method to get color state list.

textView.setTextColor(ContextCompat.getColorStateList(context, R.color.text_color))

Third, enable(true) or disable(false) based on your requirements,

textView.isEnabled = true //when item is highlighted

Happy coding...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!