The easiest way is to use ToggleButton
which can be checked
or not checked
. As a background
you can set file with states
.
You can create layout with them:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="40dp">
<ToggleButton
android:id="@+id/toggle_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/background" />
<ToggleButton
android:id="@+id/toggle_button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:background="@drawable/background"
android:checked="true" />
</LinearLayout>
As background
you can set file which contains list of states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/blue_shape" android:state_checked="true" />
<item android:drawable="@drawable/grey_shape" />
</selector>
And all of the states (checked
and default
- last one) can be shapes:
res > drawable > grey_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#D6D6D6" />
<corners android:radius="50dp" />
<stroke
android:width="2dp"
android:color="#727272" />
</shape>
res > drawable > blue_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#81D7FF" />
<corners android:radius="50dp" />
<stroke
android:width="2dp"
android:color="#1890D1" />
</shape>
You can expect different backgound when button is checked
and not checked