由于 appcompat v7 缺少 a SwitchCompatPreference
,因此似乎有必要自己创建它。
如何做到这一点?我用谷歌搜索了一下,找到了一个DialogPreference
. 我试图采用它,SwitchCompatPreference
但在我的 xml 布局中它总是说这个类在首选项 xml 中是不允许的。
我需要做什么?
由于 appcompat v7 缺少 a SwitchCompatPreference
,因此似乎有必要自己创建它。
如何做到这一点?我用谷歌搜索了一下,找到了一个DialogPreference
. 我试图采用它,SwitchCompatPreference
但在我的 xml 布局中它总是说这个类在首选项 xml 中是不允许的。
我需要做什么?
您不需要创建新组件。
首先,您应该使用CheckBoxPreference
SwitchPreference 而不是 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" />
然后,到您的SwitchPreference CheckBoxPreference中PreferenceFragment
,
yourSwitch = findPreference("key_for_this_component");
yourSwitch.setWidgetLayoutResource(R.layout.l_switch);
或者,直接到您的 CheckBoxPreference,
android:widgetLayout="@layout/l_switch"
这将强制 CheckBoxPreference 使用该SwitchCompat
样式。