Android AppCompat v21 provides SwitchCompat does not provide SwitchCompatPreference

Based on the currently accepted answer, and cgollner's gist, if you only take the xml layout from there: https://gist.github.com/cgollner/3c7fe2f9d34aee38bd0c

And do this:

<CheckBoxPreference
            android:widgetLayout="@layout/preference_switch_layout"
            android:defaultValue="off"
            android:key="key1"
            android:title="@string/title1" />

Instead of this (adding the layout from source with setWidgetLayoutResource):

<com.cgollner.unclouded.preferences.SwitchCompatPreference
            android:defaultValue="off"
            android:key="key1"
            android:title="@string/title1" />

Then the animations will also work both on lollipop and below using the same xml.


I build a little something for myself, SwitchCompatPreference.java. Extending SwitchPreference turned out to be the easiest way to build this. Sadly, SwitchCompat doesn't inherit from Switch, so the original SwitchPreference requires a slight modification. The preference is used as follows:

<me.barrasso.android.volume.ui.SwitchCompatPreference
        android:icon="@drawable/icon"
        android:key="key"
        android:defaultValue="false"
        android:widgetLayout="@layout/pref_switch"
        android:title="@string/title"
        android:summary="@string/summary" />

The layout is super-simple, tweak it as needed.

<?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/toggle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:textIsSelectable="false"
    android:textStyle="bold" />

Here is a code snippet displaying material Switches even on older versions. https://gist.github.com/cgollner/5b31123c98b2c1cad8dc https://gist.github.com/cgollner/3c7fe2f9d34aee38bd0c

Reference: https://plus.google.com/118168530059850940658/posts/badausxo1J6