How to set button selection color along with rounded corners in android?

Bharath picture Bharath · Sep 14, 2012 · Viewed 26k times · Source

I want to set a rounded corner for a button in android along with changing the button color on when selected. I am doing the following things.

drawable/push_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item android:state_pressed="true"  android:drawable="@color/green"/>
    <item android:state_focused="true"  android:drawable="@color/green"/>
    <item android:state_focused="false"  android:drawable="@color/green"/>
    <item android:state_pressed="false" android:drawable="@color/red"/>
    <item  android:drawable="@drawable/push_button_background"/>         
</selector>

drawable/push_button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    >
    <solid android:color="#3F4040"/>
    <corners 
    android:radius="7dp"
    />
</shape>

and in code, I am using

android:background="@drawable/push_button"

Here, the problem is, button colors are setting properly when selected & deselected. But, rounded corners are not working.

How to do that? If I use

android:background="@drawable/push_button_background"

then, rounded corners are working but the button color change on selection is not working

How to implement this?

I have referred this link. Even then no help!!

Answer

Bharath picture Bharath · Sep 16, 2012

I have found answer for my question with few trial & error attempts.

Here is the solution.

<?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="@color/green"/>
    <corners 
    android:radius="7dp"/>
    </shape>
 </item>

 <item android:state_focused="true" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/green"/>
    <corners 
    android:radius="7dp"/>
    </shape>
 </item>

 <item android:state_focused="false" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/red"/>
    <corners 
    android:radius="7dp"/>
    </shape>   
 </item>

 <item android:state_pressed="false" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/red"/>
    <corners 
    android:radius="7dp"
    />
    </shape>
 </item> 

</selector>