我正在尝试显示一个 switchPreference,它允许用户根据英里或公里显示距离。我正在使用 SwitchPreferenceCompat 支持库。根据库,我可以使用 textSwitchOff 和 textSwitchOn 向开关添加文本。我只想在我的开关中添加“公里”或“英里”,以便用户知道显示的是哪个指标。
根据 this doc ,我只需要下面的代码:
<android.support.v7.preference.PreferenceCategory
android:layout="@layout/preferences_category"
android:title="Distance" >
<android.support.v7.preference.SwitchPreferenceCompat android:title="KM or Miles"
android:key="kmormiles"
android:switchTextOff="miles"
android:switchTextOn="km"
android:defaultValue="true"/>
</android.support.v7.preference.PreferenceCategory>
然而,开关看起来只是一个普通开关,开关本身没有额外的文字。
如何让它与 textOn 和 textOff 一起显示?
我还尝试了以下方法:
addPreferencesFromResource(R.xml.preferences);
kmormiles = (SwitchPreferenceCompat) findPreference("kmormiles");
kmormiles.setSwitchTextOff("Km");
kmormiles.setSwitchTextOn("miles");
还是不行。我在两个不同的 genymotion 模拟器上尝试它,API 16 和 API 21。
最佳答案
由于 SwitchPreferenceCompat
默认使用 SwitchCompat
小部件,Android Switch widget textOn and textOff not working in Lollipop在这里也有一个应用程序。和第一个声明
Text is not shown by default under Material theme since the switch widget assets don't work well with text.
还解释了为什么结果看起来一点都不好。
SwitchPreferenceCompat
类本身不提供设置是否应显示开/关文本的可能性。因此,使其工作的一种方法可能是覆盖 onBindViewHolder(PreferenceViewHolder)
方法以编程方式设置它。
另一种可能更好的方法是利用您无论如何都被迫与首选项兼容库一起使用的主题机制。您不能直接为 View 设置任何属性,但您可以定义要与 android:widgetLayout
一起使用的布局。因此,只需创建您自己的偏好主题覆盖即可
<style name="MyPreferenceThemeOverlay" parent="PreferenceThemeOverlay">
<item name="switchPreferenceCompatStyle">@style/MySwitchPreferenceCompat</item>
</style>
使用您自己的开关偏好样式
<style name="MySwitchPreferenceCompat" parent="Preference.SwitchPreferenceCompat">
<item name="android:widgetLayout">@layout/pref_stack</item>
</style>
使用稍微修改过的default switch layout
<android.support.v7.widget.SwitchCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/switchWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:clickable="false"
android:focusable="false"
app:showText="true" />
您在编写代码时应牢记的另一件事是compat 功能本身。通过显式使用 android.support.v7.preference.SwitchPreferenceCompat
,您永远不会获得更适合充气机自动识别的较新设备的版本,例如当前唯一可用的替代方案 android.support.v14 .preference.SwitchPreferenceCompat
。不过,这可能需要您多做一些工作。
编辑:这是发帖人执行上述建议的结果,正如他正确提到的那样,结果看起来一点也不好:
关于android - SwitchPreferenceCompat : android:switchTextOff/switchTextOn doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415907/