如何在Android中为SwitchPreference小部件设置自定义样式或其他可绘制的背景选择器?

(注意:不是常规的Switch小部件,我的意思是SwitchPreference/PreferenceActivity中使用的标准PreferenceFragment小部件)

最佳答案

您必须为开关本身创建一个自定义布局,并且可以像这样动态地应用它。

preference.setWidgetLayoutResource(R.layout.custom_switch);

但是,我将详细介绍如何实现这一目标。

因此,您可以在XML文件中定义自己的首选项,例如 preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <PreferenceCategory android:title="YOUR_CATEGORY_TITLE" >
        <SwitchPreference
            android:key="SWITCH"
            android:title="YOUR_TITLE_FOR_SWITCH" />
    </PreferenceCategory>
</PreferenceScreen>

然后在您的PreferenceActivty类内的onCreate()方法中读取它:
    SwitchPreference pref = (SwitchPreference) findPreference(getString(R.string.SWITCH));
    //pref.setChecked(true); // You can check it already if needed to true or false or a value you have stored persistently
    pref.setWidgetLayoutResource(R.layout.custom_switch); // THIS IS THE KEY OF ALL THIS. HERE YOU SET A CUSTOM LAYOUT FOR THE WIDGET
    pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // Here you can enable/disable whatever you need to
            return true;
        }
    });

custom_switch 布局如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_switch_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:textColor="@android:color/white"
    android:textIsSelectable="false"
    android:textSize="18sp"
    android:textStyle="bold"
    android:track="@drawable/switch_track"
    android:thumb="@drawable/switch_thumb"/>

对于此切换,您将有2个选择器用于轨道 thumb 属性。
这些选择器的可绘制对象可以使用tasomaniac建议的Android Holo Color Generator生成。在这种情况下,您要做的就是复制生成的drawable文件夹的内容(仅适用于drawable-hdpi,drawable-mdpi,drawable-xhdpi,drawable-xxhdpi)。但是您可以为所需的每个状态创建自定义 View 。

这些选择器的外观如下:
switch_track:
<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/switch_bg_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/switch_bg"/>

</selector>

switch_thumb:
<?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android">

     <item android:drawable="@drawable/switch_thumb_disabled" android:state_enabled="false"/>
     <item android:drawable="@drawable/switch_thumb_pressed" android:state_pressed="true"/>
     <item android:drawable="@drawable/switch_thumb_activated" android:state_checked="true"/>
     <item android:drawable="@drawable/switch_thumb"/>

</selector>

就是这样。该解决方案帮助了我。如果我省略了某些内容,请告诉我,我将纠正问题。

10-07 19:41
查看更多