创建自己的SwitchCompat preference [英] Create own SwitchCompat Preference

查看:732
本文介绍了创建自己的SwitchCompat preference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于appcompat V7缺少 SwitchCompat preference 这似乎是有必要由我自己来创建它。

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

如何才能实现这一目标?我用Google搜索了一下,发现一个教程为对话preference 。我试图通过它的 SwitchCompat preference 但是在我的XML布局总是说,这个类是不是在preference XML允许的。

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.

什么是我需要做什么?

推荐答案

您并不需要创建一个新的组成部分。

You do not need to create a new component.

首先,你应该使用复选框preference ,而不是切换preference,以支持较低的API。

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

使用现有的 android.support.v7.widget.SwitchCompat 小部件,创建一个新的布局文件,例如 l_switch.xml 。使用下面的code:

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" />

那么,你的开关preference 复选框preference preferenceFragment

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

或者,您的复选框preference直接,

or, to your CheckBoxPreference directly,

android:widgetLayout="@layout/l_switch"

这将迫使复选框preference使用 SwitchCompat 的风格。

This will force the CheckBoxPreference to use the SwitchCompat style.

这篇关于创建自己的SwitchCompat preference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆