创建自己的SwitchCompat首选项

the*_*nut 5 android android-appcompat preference switchcompat

由于appcompat v7缺失了SwitchCompatPreference,似乎有必要自己创建它.

怎么能实现这一目标?我google了一下,找到了一个教程DialogPreference.我试图采用它,SwitchCompatPreference但在我的xml布局中,它总是说在偏好xml中不允许这个类.

我需要做什么?

jyo*_*Pro 24

您无需创建新组件.

首先,您应该使用CheckBoxPreference而不是SwitchPreference,以支持较低的API.

例如,使用现有android.support.v7.widget.SwitchCompat小部件创建新的布局文件l_switch.xml.使用以下代码:

<?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" />
Run Code Online (Sandbox Code Playgroud)

然后,到你的SwitchPreference CheckBoxPreferencePreferenceFragment,

yourSwitch = findPreference("key_for_this_component");
yourSwitch.setWidgetLayoutResource(R.layout.l_switch);
Run Code Online (Sandbox Code Playgroud)

或者,直接到你的CheckBoxPreference,

android:widgetLayout="@layout/l_switch"
Run Code Online (Sandbox Code Playgroud)

这将强制CheckBoxPreference使用该SwitchCompat样式.

  • 我有同样的问题.我会找到一个修复程序,并更新这篇文章. (2认同)