dwbrito dwbrito - 1 year ago 104
Android Question

Android customized button; changing text color

I made a button that changes the background drawable on different states, this way:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_location_pressed" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/btn_location_pressed"/> <!-- focused -->
<item android:drawable="@drawable/btn_location"/> <!-- default -->

The problem here is that I'm also trying to change the textColor as I do with the drawable but I'm not being able to. I already tried android:textColor and android:color but the first doesn't work whilst the seconds changes my background.

The next code is part of my layout. Regarding to the text color it only works for the normal state text color, thus not changing it to the white one while pressed

<Button android:id="@+id/location_name"

Has anybody got a clue?

Answer Source

Create a stateful color for your button, just like you did for background, for example:

<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="#000000" />
    <item android:state_focused="false" android:state_pressed="true" android:color="#000000" />
    <item android:color="#ffffff" />

Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download