Create own SwitchCompat Preference

后端 未结 1 1432
别那么骄傲
别那么骄傲 2020-12-29 00:15

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 b

相关标签:
1条回答
  • 2020-12-29 00:52

    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.

    0 讨论(0)
提交回复
热议问题