In this tutorial we will see how we can change the default appearance of a button. For this we need to customize three different states of button i.e. default state, pressed state and focused state.
Output will be as:(When button is pressed)
Xml files:
1. activity_main(res/layout):
2. custom_button.xml(res/drawable):Output will be as:(When button is pressed)
Xml files:
1. activity_main(res/layout):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical"
>
<Button
android:id="@+id/button1"
android:layout_width="200dp"
android:layout_height="50dp"
android:background="@drawable/custom_button"
android:text="Button"
/>
</LinearLayout>
Now here we need to create a new xml file(custom_button.xml) under res/drawable that will customize the three states of button.
<?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/change"
>
</item>
<item android:state_focused="true"
android:drawable="@color/change"
>
</item>
<item android:drawable="@color/default_color">
</item>
</selector>
We also need to create colors.xml under res/values to define the colors.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="change">#5F9EA0</color>
<color name="default_color">#ACACAC</color>
</resources>