As already mentioned by K-Ballo, you can use StateListDrawable to implement a view with different graphics depending on the state. In your case, Button is a view in which two states are pressed on the button and the button is not pressed.
We need to create the buttonselector.xml file in the folder with the picture
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/button_not_pressed" android:state_pressed="false" android:state_selected="false"/> <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/> </selector>
Create two separate xml files for button state
button_not_pressed.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="#FFFFFF" android:centerColor="#FFFFFF" android:endColor="#FFFFFF" android:angle="270" /> </shape>
button_pressed.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="#FF0000" android:centerColor="#FF0000" android:endColor="#FF0000" android:angle="270" /> </shape>
You will notice two html color codes # FF0000 and #FFFFFF, which represent the background color of the button according to the state.
In the main.xml file, where you set the style of your custom button
<Button android:id="@+id/customButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/buttonselector" android:text="test" android:textColor="#000000" />
In your activity class add the following two lines
Button customButton = (Button) findViewById(R.id.customButton); customButton.setBackground(getResources().getDrawable(R.drawable.buttonselector));
Hope this helps
Vikas
source share