0

I have a Button that uses a shape as it's background.

The shape will have different color based on the state of the Button

Is it possible for me to specify the color of each state inside the Button's xml? I am sorry for the newbie question. Any guide please?

button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dp" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="10dp" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dp" />
            <solid android:color="@color/colorWhite" />
        </shape>
    </item>
</selector>

How it is currently called

    <Button
        android:id="@+id/loginButton"
        android:background="@drawable/button_background"
        android:text="@string/login_button_title"/>
JayVDiyk
  • 4,277
  • 22
  • 70
  • 135

2 Answers2

1

This is a bit of a late answer, but I described what you want in detail in this post, even how to produce ripples in your background, you might want to check it out

Community
  • 1
  • 1
FabioR
  • 696
  • 9
  • 18
0

Create a color state list in XML.

res/color/button_bg.xml:

<selector xmlns:android="...">
    <item android:color="@color/colorPrimary" android:state_focused="true" />
    <item android:color="@color/colorPrimary" android:state_pressed="true" />
    <item android:color="@color/colorWhite" />
</selector>

Then your shape drawable can simply use this color resource:

res/drawable/button_bg.xml

<shape xmlns:android="..."
    android:shape="rectangle"  >

    <corners android:radius="10dp" />
    <solid android:color="@color/button_bg" />
</shape>
Karakuri
  • 38,365
  • 12
  • 84
  • 104