Customized circular checkbox in Android

不想你离开。 提交于 2019-12-08 08:56:27

Custom Checkbox with two drawable image.

1. In .xml file

<android.support.v7.widget.AppCompatCheckBox
   android:id="@+id/checkBox"
   android:layout_width="40dp"
   android:layout_height="40dp"
   android:layout_gravity="center"
   android:background="@drawable/checkbox_selector"
   android:button="@color/white"
   android:checked="true" />

2. Create checkbox_selector.xml in drawable folder.

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

3. Add checked.png and cansel.phd image in drawable folder from the below link

https://icons8.com/icon/set/yes/all

And

https://icons8.com/icon/set/cross/all

4. Checkbox click event

AppCompatCheckBox checkBox = (AppCompatCheckBox) view.findViewById(R.id.checkBox);

checkBox.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

       if (checkBox.isChecked()){
      checkBox.setChecked(false);
       }else {
         checkBox.setChecked(true);
       }
         }
});

You need to give size to your drawable when you want to use it for button attribute.

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
   <stroke
       android:width="1dp"
       android:color="#78d9ff"/>
   <solid android:color="#79bfea"/>
   <size
       android:width="20dp"
       android:height="20dp"/>
</shape>

And apply to CheckBox with android:button.

Also since this is a checkbox, you should use selector to have checked and unchecked state.

An example of selector is

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/normal"
          android:state_checked="false"/>
    <item android:drawable="@drawable/checked"
          android:state_checked="true"/>
    <item android:drawable="@drawable/normal"/>
</selector>

You may not be looking now, however i have code which seems to make circular image with checkbox please have a look at my answer given on another thread.

Click here to view answer on another thread

check my answer on the question in the link, with that you will be able to create and customise your checkbox without the need of coding

answer here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!