How to apply custom image to checkbox in android

I am trying to apply a custom image to a checkbox in android, for this I create a check_custom.xml file in which I define a custom image for different states of the checkbox, for example:

 <item android:state_checked="true" android:drawable="@drawable/btn_check_on" /> <!-- checked --> <item android:state_checked="false" android:drawable="@drawable/btn_check_off" /> <!-- unchecked --> <item android:state_focused="true" android:drawable="@drawable/btn_check_onfocus" /> <!--on focus--> <item android:drawable="@drawable/btn_check_off" /> <!-- default --> 

Three different images in three states on checked, on focus and on unverified, and then I assign this xml file to the background attribute with flags, but I do not get the desired result, this method applies a non-standard image, as well as the default image.

+46
android
Mar 03 2018-11-11T00:
source share
4 answers

Salman, install android:button instead of android:background . See Also Custom checkbox and android

+92
Mar 03 '11 at 6:18
source share

I did not like the appearance of the default checkbox when the background layout was dark, so I changed it with the xml selector to have a white background in the button.

The selector is needed in android: button = "@ drawable / selector_check"

  <CheckBox android:id="@+id/checkBox1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:text="Show password" android:textColor="@color/white" android:button="@drawable/selector_check" > 

And here is the content of "drawable / selector_check.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="@android:drawable/checkbox_on_background" /> <!-- checked --> <item android:state_checked="false" android:drawable="@android:drawable/checkbox_off_background" /> <!-- unchecked--> </selector> 

And this is the result:

enter image description here

+16
May 20 '13 at 8:57
source share

Copy the btn_check.xml file from the android-sdk / platform / android - # / data / res / drawable website to your project folder and change the image states 'on' and 'off' to your custom images.

Then your xml just needs android:button="@drawable/btn_check"

 <CheckBox android:button="@drawable/btn_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" /> 

If you want to use different default icons for android , you can use android:button="@android:drawable/..."

+5
Aug 01 2018-12-18T00:
source share

 <item android:drawable="@drawable/ON" android:state_checked="false"/> <item android:drawable="@drawable/OFF" android:state_checked="true"/> <item android:drawable="@drawable/ON"/> 

+3
Mar 03 '15 at 13:16
source share



All Articles