【发布时间】:2017-03-31 02:47:03
【问题描述】:
我正在使用 PreferenceFragmentCompat,但我得到了这个运行时异常:
Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
令人困惑的部分是我的偏好定义不包含任何 RecyclerViews。这是 XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android" >
<android.support.v7.preference.PreferenceCategory
android:layout="@layout/preference_first_category"
android:title="@string/pref_category_general">
<android.support.v7.preference.SwitchPreferenceCompat
android:title="@string/pref_demo_mode"
android:key="@string/pref_demo_mode_key"
android:defaultValue="true"
android:persistent="true" />
</android.support.v7.preference.PreferenceCategory>
<android.support.v7.preference.PreferenceCategory
android:layout="@layout/preference_category"
android:key="serverCategory"
android:persistent="false"
android:title="@string/pref_category_server">
<android.support.v7.preference.EditTextPreference
android:title="@string/pref_server_control_ip"
android:summary="@string/pref_enter_ip_address"
android:defaultValue="@string/pref_enter_ip_address"
android:key="@string/pref_ctrl_ip_key"
android:selectAllOnFocus="true"
android:singleLine="true"
android:persistent="true" />
<android.support.v7.preference.EditTextPreference
android:title="@string/pref_server_admin_ip"
android:summary="@string/pref_enter_ip_address"
android:defaultValue="@string/pref_enter_ip_address"
android:key="@string/pref_admin_ip_key"
android:selectAllOnFocus="true"
android:singleLine="true"
android:persistent="true" />
<android.support.v7.preference.EditTextPreference
android:title="@string/pref_server_network_mask"
android:defaultValue="@string/pref_enter_network_mask"
android:summary="@string/pref_enter_network_mask"
android:key="@string/pref_network_mask_key"
android:selectAllOnFocus="true"
android:singleLine="true"
android:persistent="true" />
</android.support.v7.preference.PreferenceCategory>
</android.support.v7.preference.PreferenceScreen>
我查看了参考 API,可以清楚地看到 PreferenceFragmentCompat 确实支持 RecyclerView,但我看到了几个工作代码示例,它们的首选项中没有 RecyclerView 视图,因此 RecyclerView 似乎不是强制性的。
我需要重写任何 RecyclerView 方法吗?没有 RecyclerView 的其他工作示例不需要,所以我不知道如何解决这个问题。
谢谢, -安德烈斯
【问题讨论】:
-
只是一些附加信息:我已经绊倒了preferenceTheme异常。结果是 PreferenceFragmentCompat 需要preferenceTheme,所以我已经将它添加到样式中并且不再出现该异常。
-
您是否覆盖了
onCreateView的PreferenceFragmentCompat?发布您的代码。 -
是的,我将同时覆盖 onCreateView() 和 onCreatePreferences()。在 onCreatePreferences() 中,我唯一要做的就是调用 addPreferencesFromResources()。
-
你为什么要覆盖
onCreateView()?你提供什么布局,你想运行什么代码?PreferenceFragmentCompat必须在onCreateView()中设置首选项。 -
嗨@AndresGonzalez,我遇到了完全相同的问题。你能解决这个问题吗?
标签: android android-fragments android-recyclerview