Android Button Design
A selector is used to define a different behaviour for different states of the Button.What are drawable states?
Each of the following events of a view (Button or any other kind of view) are a type of state:
state_pressedstate_focused is when you hover over the widget. Typically works only on emulators.
state_selected
state_focused
state_enabled
Selector for different background colors.
The following selector file btn_bg_selector.xml contains the code for setting different background colors on a button for different states.
<?xml version="1.0" encoding="utf-8"?>We set the above drawable selector file on our button in the activity_main.xml as:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/red"/>
<item android:state_focused="true" android:drawable="@color/yellow"/>
<item android:drawable="@color/green"/>
</selector>
<ButtonSelector for Disabled Button
android:id="@+id/btnBgSelector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@drawable/btn_bg_selector"
android:padding="8dp"
android:text="Colored Selector" />
The following selector btn_bg_selector_disabled.xml is used on a button which is not enabled.
<?xml version="1.0" encoding="utf-8"?>For the above selector to work, we need to specify android:enabled as false.
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@color/yellow"/>
<item android:state_pressed="true" android:drawable="@color/red"/>
<item android:drawable="@color/green"/>
</selector>
<ButtonSelector with Different Drawables
android:id="@+id/btnBgSelectorDisabled"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@drawable/btn_bg_selector_disabled"
android:enabled="false"
android:padding="8dp"
android:text="Color Selector Disabled" />
We can set a different drawable image to be displayed based upon the state of the button.
The selector code that does so is present in the file btn_drawable_selector.xml
<?xml version="1.0" encoding="utf-8"?>For the sake of convenience we’ve done the former here:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sad" android:state_pressed="true"/>
<item android:drawable="@drawable/happy" android:state_focused="true"/>
<item android:drawable="@drawable/happy"/>
</selector>
<Button
android:id="@+id/btnDrawableSelector"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:background="@drawable/btn_drawable_selector"
android:padding="16dp" />