Disabling Custom Preference but also provide a layout for when it is disabled?

212 Views Asked by At

Is there an XML attribute so that I can set the appearance of my custom Preference with attribute: android:enabled="false"?

For example, if you use a default CheckBoxPreference and disable it, it will be greyed out and indicate to the user that it is disabled and clicking it will probably do nothing.

But with my custom preference, disabling it will not make it look any different, and thus it will confuse the user when they click on it and it does nothing.

1

There are 1 best solutions below

0
gpl On BEST ANSWER

Create drawable checkbox.xml file consisting of <selector> which sets checkbox button's image depending on its status:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
          android:drawable="@drawable/checkbox_checked" /> <!-- checked -->
    <item android:state_checked="false" 
        android:drawable="@drawable/checkbox_unchecked" /> <!-- default -->
</selector>

You can even use colors in place of these drawables.

In your custom checkbox preference checkbox_preference.xml using this drawable add checkbox's button. Place this file in layout folder:

<CheckBox android:id="@+android:id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/checkbox" />

Inflate this using your prefs.xml . The layout attribute is used to put the custom layout with the custom checkbox.

 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="@string/category_title">
        
    <CheckBoxPreference
    android:key="preferenceKey"
    android:title="@string/preferenceTitle"
    android:defaultValue="false"
    android:layout="@layout/checkbox_preference"
    />
    </PreferenceCategory>
</PreferenceScreen>