问题
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?
回答1:
Use below line of code, i think it will work
yourcheckbox.setButtonDrawable(yourdrawable);
回答2:
Simple way
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>
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"/>
回答3:
Use This
shuffle.setButtonDrawable(R.drawable.custom_checkbox_selector);
XML code;
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/radiobutton_checked" android:state_checked="true"/>
<item android:drawable="@drawable/radiobutton_unchecked" android:state_checked="false"/>
</selector>
回答4:
This works for me:
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_checkbox"
android:button="@null"/>
回答5:
If you use sdk 28 (androidx) and above try to use
androidx.appcompat.widget.AppCompatCheckBox
instead of
Checkbox
来源:https://stackoverflow.com/questions/31183713/android-replace-checkbox-style-with-custom-drawable-selector