首选项支持库 - SwitchPreference无法正常工作

use*_*815 24 android android-preferences android-support-library android-switch

几天前谷歌推出了Preference Support Library(Link).我刚刚尝试在我的应用程序中实现它,虽然看起来它不能用于SwitchPreferences哪个是奇怪的,因为谷歌表示我们可以使用与以前相同的XML文件,并且明确表示SwitchPreferences现在可用于所有API 7+设备.

报价(来源)

[...]并使用相同的首选XML文件(http://goo.gl/wOcIxI)添加首选项,同时向所有API 7+设备添加对SwitchPreference等元素(以前仅在API 14+设备上可用)的支持.[...]

错误信息

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.package/com.my.package.Main}: android.view.InflateException: Binary XML file line #4: Error inflating class (not found)SwitchPreference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Run Code Online (Sandbox Code Playgroud)

相关部分显然是Binary XML file line #4: Error inflating class (not found)SwitchPreference.

Java代码

public class FragmentSettings extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
        addPreferencesFromResource(R.xml.preferences);
    }
}
Run Code Online (Sandbox Code Playgroud)

的preferences.xml

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

    <SwitchPreference
        android:key="pref_something"
        android:summary="Lorem ipsum dolor sit amet"
        android:title="Lorem ipsum" />

</PreferenceScreen>
Run Code Online (Sandbox Code Playgroud)

所以基本上问题是:我做错了什么,或者这确实是偏好支持库的错误?

Ary*_*afi 61

SwitchPreference在API级别14中添加.如果您使用的是首选项支持库v7,则必须使用SwitchPreferenceCompat.

<SwitchPreferenceCompat
    android:key="pref_something"
    android:summary="Lorem ipsum dolor sit amet"
    android:title="Lorem ipsum" />
Run Code Online (Sandbox Code Playgroud)

  • 而已.我已经考虑过这样的事情,遗憾的是我找不到任何东西 - 有时候文档很糟糕.Google应该在[SwitchPreference](http://developer.android.com/reference/)上提及[SwitchCompatPreference](https://developer.android.com/reference/android/support/v7/preference/SwitchPreferenceCompat.html). android/preference/SwitchPreference.html)页面. (3认同)