Thursday, 28 July 2011

Android: how to use ColorStateList

(1) Create a folder in the 'res' folder and name it 'color'.

(2) Create an Android xml file in the new 'color' folder and name it 'mycolorlist.xml' or another name of your choosing. Place the following markup in your new xml file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="" >
 android:state_pressed="false" />
 android:state_pressed="true" />

Be sure that 'mycolor1' and 'mycolor2' are colours specified in your 'res/values/colors.xml' file. If you're not sure how to specify colors in your 'colors.xml' file, see the end of this post.

(3) Add the following code to the TextView to which you wish to apply the new ColorStateList...
... where myTextView is a TextView instance.

Done! Now when myTextView is pressed, its colour will be 'mycolor2', and otherwise its colour will be 'mycolor1'.

Lastly, here is an example of what your 'colors.xml' file might look like...
<?xml version="1.0" encoding="utf-8"?>
 <color name="mycolor1">#ff005eff</color>
 <color name="mycolor2">#ff86C4ed</color>
... which specifies two different shades of blue.


Anonymous said...

Hey thanks it worked :)

adil said...

No prob. Glad I could be of assistance :)

Unknown said...

great tutorial. i need it function, because when i just settextcolor, the color is going to black.

Anonymous said...

Thanks for the post. Its working perfectly.