Android : change button text and background color

Maelig picture Maelig · Oct 16, 2013 · Viewed 255.6k times · Source

How can I change both text and background colors when my button is pressed, with xml ?

To change text color I can do :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="mycolor"/>
    <item android:color="mycolor2/>
</selector>

To change the background I can do (using it in a selector/item with drawable reference) :

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FF0079FF" />
</shape>

But how can I do both ? Let's say I want to have :

  • Default : black text / white background
  • Pressed : white text / blue background

EDIT : answer

I totaly forgot that the background and text color are managed separately, so this is how I did it :

<Button
    android:textColor="@color/filtersbuttoncolors"
    android:background="@drawable/mybackgroundcolors" />

In mybackgroundcolors.xml I manage the background and in filtersbuttoncolors.xml I manage the text color. In both xml files I manage the status (pressed, selected, default)

Answer

Mitesh Shah picture Mitesh Shah · Oct 16, 2013

Here is an example of a drawable that will be white by default, black when pressed:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid
                android:color="#1E669B"/>
            <stroke
                android:width="2dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="6dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>

    </item>
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:endColor="#1E669B"
                android:startColor="#1E669B"/>
            <stroke
                android:width="4dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="7dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>
    </item>
</selector>