Question

How to create this type of checkbox in android when it pressed. I tried . May I know what is the correct way to achieve my objective?Maybe this question too basic, but i did't find any suitable solution.Please Help me out.

I want to create Like this enter image description here

When it unchecked it will looks like :enter image description here

Here is my XML code for checkbox:

 <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:button="@drawable/custom_checkbox"/>

Here is custom_checkbox.xml

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/checked" />
    <item android:state_pressed="true"
        android:drawable="@drawable/checked" />
    <item android:drawable="@drawable/unchecked" />
</selector>

Here is checked.xml

 <?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#54d66A" android:endColor="#54d66A" android:angle="270"/>
    <stroke android:width="4px" android:color="#ffc0c0c0" />
    <size android:height="20dp" android:width="20dp"/>
</shape>

Here is my output: enter image description here

Was it helpful?

Solution

You need to create a drawable with layer-list with two items as rectangle shape . one for the background and other as stroke with some margin.

   <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item>
    <shape android:shape="rectangle">
        <gradient android:startColor="#54d66A" android:endColor="#54d66A" android:angle="270"/>
        <size android:height="20dp" android:width="20dp"/>
    </shape>
  </item>
  <item android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp">
    <shape android:shape="rectangle" >
        <stroke android:width="2dp" android:color="#ffc0c0c0" />
    </shape>
  </item>
 </layer-list>

And , set this drawable as state_checked background.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top