Create own SwitchCompat Preference

梦想的初衷 提交于 2019-11-30 04:05:50

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.

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