Custom Checkbox in Android
It's a very common practice to use a checkbox in our app. We all know how it works. Right ??
What if we need a customize the checkbox ? Well, by saying customize a checkbox, I actually mean to set a customize background for the checkbox. Means, if a user click over an unchecked checkbox the checked checkbox should appear as a background instead of the default ticked checbox provided by android. Similar thing should be happened in the later case.
Soon or later you will need to learn this feature in order to implement for your app. So better learn it today itself. So let’s start....
1. Create an xml file (say myselector.xml) and put it inside the drawable folder(you can put it to some other location as well).
Copy and paste this ....to your newly created xml file.
checkbox_selector.xml(My xml file name)
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:state_focused="true" android:drawable="@drawable/check" /> <item android:state_checked="false" android:state_focused="true" android:drawable="@drawable/uncheck" /> <item android:state_checked="false" android:drawable="@drawable/uncheck" /> <item android:state_checked="true" android:drawable="@drawable/check" /> </selector>
Remember to replace the
android:drawable="@drawable/check" ....with your “check” image/icon android:drawable="@drawable/uncheck" ....with your “uncheck” image/icon 2. Include “checkbox” tag in Your Activity’s xml file <RelativeLayout ..............................(you can use any layout of your choice) android:id="@+id/checkbox" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:id="@+id/checkBox4" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="@drawable/checkbox_selector"
(use your file name here)
android:button="@drawable/uncheck">
(Uncheck has been set but you can change it) </RelativeLayout>
If you didn’t get any error till now....You are Done !! Compile and Run your project. You should not face any difficulty in using this feature. In case you do...leave me a message below.
The same concept should be applied for the radio button as well. I have not tried with the radio buttons though. But I guess there shouldn’t be any issue. Anyways....enjoy programming !!