Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android replace checkbox style with custom drawable selector

I have tried to make a xml selector with the following:

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

and when I try to set the backgroundDrawable to the checkBox the checkbox doesn't replace the CheckBox style too:

  shuffle.setBackground(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.shuffle, null));

Following this question: Change icons of checked and unchecked for Checkbox for Android I need to set the button drawable with my xml: android:button="@drawable/checkbox" but I can't do this because I'm creating the CheckBox programmatically. Is there a way how to achieve this?

like image 630
Marian Pavel Avatar asked Jul 02 '15 11:07

Marian Pavel


2 Answers

Simple way

  1. Create a new layout in drawable folder and name it custom_checkbox (You can rename also)

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/Checked_image_name"android:state_checked="true"/>
    <item android:drawable="@drawable/Unchecked_image_name" android:state_checked="false"/>
    </selector>
    
  2. Use this in your layout activity

    <CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox"/>
    
like image 111
Sunil Avatar answered Sep 28 '22 20:09

Sunil


Use below line of code, i think it will work

yourcheckbox.setButtonDrawable(yourdrawable); 
like image 40
Madhu Avatar answered Sep 28 '22 21:09

Madhu