Search code examples
androidandroid-appcompatpreferenceswitchcompat

Create own SwitchCompat Preference


Since the appcompat v7 is missing a SwitchCompatPreference it seems like it's necessary to create it by myself.

How can this be achieved? I googled a bit and found a tutorial for a DialogPreference. I tried to adopt it for a SwitchCompatPreference but in my xml layout it always says that this class is not allowed in the preference xml.

What do I need to do?


Solution

  • You do not need to create a new component.

    First of all, you should use CheckBoxPreference instead of SwitchPreference, in order to support lower APIs.

    Using the existing android.support.v7.widget.SwitchCompat widget, create a new layout file, for example l_switch.xml. Use the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.SwitchCompat xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/checkbox" <!-- IMPORTANT -->
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:clickable="false" <!-- IMPORTANT -->
        android:focusable="false" <!-- IMPORTANT -->
        android:gravity="center" />
    

    Then, to your SwitchPreference CheckBoxPreference in PreferenceFragment,

    yourSwitch = findPreference("key_for_this_component");
    yourSwitch.setWidgetLayoutResource(R.layout.l_switch);
    

    or, to your CheckBoxPreference directly,

    android:widgetLayout="@layout/l_switch"
    

    This will force the CheckBoxPreference to use the SwitchCompat style.