How to apply custom image to checkbox in android
I'm trying to apply custom image to checkbox in android, for this I create an check_custom.xml
file in which I define custom image for different states of check box like:
<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 on three states on checked,on focus and on unchecked, and then I assign this xml file to background attribute of check boxes,but I'm not getting required result, this technique apply the custom image as well as default image both.
Salman, set android:button
instead of android:background
. See also Custom checkbox image android
I didn´t like the appearance of the checkbox default image when the background layout was dark, so I changed it using a xml selector in order 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 the following 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:
Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.
Then your xml will just need 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 android icons, you can use android:button="@android:drawable/..."
<item android:drawable="@drawable/ON" android:state_checked="false"/>
<item android:drawable="@drawable/OFF" android:state_checked="true"/>
<item android:drawable="@drawable/ON"/>