Titmael Titmael - 2 days ago 5
Android Question

Android : change button text and background color

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

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"
          android:drawable="@android:color/black" /> <!-- pressed -->
    <item android:drawable="@android:color/white" /> <!-- default -->
</selector>

Also

<?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:left="10dp"
        android:top="10dp"
        android:right="10dp"
        android:bottom="10dp" />            
</shape>  

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