androidandroid-text-color

Button Press,Text Color


I need to change Button Color(normal/pressed) using Selector

res/color/test_color_button.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/button_focused"/>
<item android:state_pressed="false" android:color="@color/button_font"/>
<item android:color="@color/button_font"/>
</selector>

in code class MyButton (its extended from class Button) and I used following code to set text color

 //at Constructor 
 this.setTextColor(getResources().getColor(R.color.text_color_button));

But my problem is ,Button alwas shows default color


Solution

  • You need to create a ColorStateList object

    XmlResourceParser parser = getResources().getXml(R.color.test_color_button);
    ColorStateList colorStateList = ColorStateList.createFromXml(getResources(), parser);
    this.setTextColor(colorStateList);