change button text color when pressed

I like the solution proposed by Konstantin Burov in the other issue: Android customized button; changing text color

You can actually manage more states than just pressed and normal. But it should solve the problem.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true" 
      android:state_pressed="false" 
      android:color="#ffffff" />

<!-- Focused and pressed -->
<item android:state_focused="true" 
      android:state_pressed="true" 
      android:color="#000000" />

<!-- Unfocused and pressed -->
<item android:state_focused="false" 
      android:state_pressed="true" 
      android:color="#000000" />

<!-- Default color -->
<item android:color="#ffffff" />
</selector>

Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button_text_color"

android:textColor="@drawable/button_text_color"

Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true" 
      android:state_pressed="false" 
      android:drawable="#ffffff" />

<!-- Focused and pressed -->
<item android:state_focused="true" 
      android:state_pressed="true" 
      android:drawable="#000000" />

<!-- Unfocused and pressed -->
<item android:state_focused="false" 
      android:state_pressed="true" 
      android:drawable="#000000" />

<!-- Default color -->
<item android:drawable="#ffffff" />
</selector>

And then in the button itself do, note that this time the selector name is "button_background"

android:background="@drawable/button_background"


See the section called State List in this bit of documentation...Drawable Resources.

You can define two different Button xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define a selector which switches the drawable resources in the different states.

EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself.


Yes, you can do it like that:

layout/main_layout.xml:

.....
    <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="bonjour !"
      android:textColor="@color/button_text_color"
    />
.....

color/button_text_color.xml:

   <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:color="#c0c0c0" android:state_pressed="true"/>
     <item android:color="#ffffff"/>
   </selector>