您必须为开关本身创建自定义布局,并且可以动态应用它。
preference.setWidgetLayoutResource(R.layout.custom_switch);
但我会详细介绍并告诉你具体如何实现这一点。
因此,您可以在 preferences.xml
之类的 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 个选择器用于 track 和 thumb 属性。
这些选择器的可绘制对象可以使用tasomaniac 建议的 Android Holo 颜色生成器生成。在这种情况下,您所要做的就是复制生成的可绘制文件夹的内容(仅适用于drawable-hdpi、drawable-mdpi、drawable-xhdpi、drawable-xxhdpi)。但是您可以为您需要的每个状态创建自定义视图。
以下是这些选择器的外观:
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>
差不多就是这样。这个解决方案帮助了我。如果我遗漏了什么,请告诉我,我会更正问题。