Create own SwitchCompat Preference

孤人 提交于 2019-11-30 12:54:34

问题


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 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.

What do I need to do?


回答1:


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.



来源:https://stackoverflow.com/questions/26724566/create-own-switchcompat-preference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!