Question

I have some CheckBoxPreferences and I have no problem changing the icon for them through xml as shown below and here but since the user has other ways of triggering the checkbox's actions than directly clicking on it (i.e. perhaps in another activity or even another application) I want to be able to programmatically set the icon depending on value changes that occur along with the action. For example, if Bluetooth is on, I want the icon to be one image and when bluetooth is off, I want it to be a different image. Is it possible to programmatically change this image?

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check_box_icon"
android:clickable="true"
android:focusable="false"
android:/>
Was it helpful?

Solution

Found the solution:

I used the method found in the link that I'd provided in the question to set a selector so that I could use that with all of my CheckBoxPreferences for the different images based on the current state of the checkbox:-

<?xml version="1.0" encoding="utf-8"?>
//This is the xml selector "@drawable/checkbox"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector> 

Accordingly, the CheckBoxPreference code changes as well:-

<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content" 
android:text="new checkbox"
android:button="@drawable/checkbox"
android:clickable="true"
android:focusable="false" />

Now, I can call Checkbox.setChecked() to check whether it's enabled or not, and also to change it according to the values by setting it to true or false. So, according to the xml properties this will automatically change the icon as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top