Apply ColorStateList for TextView to show when click on it

Using ColorStateList for Textiew we can display colours when click on it.

When we need to display a text as a link, and clicked on the text starts another activity or do some action. It looks good if we display text color states, so User can know text is clicked. Here is how we can do it…

Create file in res/drawable/text_selector_red_black.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="@color/black" />
    <item android:state_focused="true" android:state_pressed="true" android:color="@color/black" />
    <item android:state_focused="false" android:state_pressed="true" android:color="@color/black" />
    <item android:color="@color/red" />
</selector>

and in color.xml file add these colors

#000000
#ff0000

Then use apply textColor property for TextView as “@drawable/text_selector_red_black” in design window. Or you can apply in coding as below

textViewObj.setTextColor(getResources().getColorStateList(R.drawable.text_selector_red_black));

Hope this helps. ­čÖé

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *