gpt4 book ai didi

android - PreferenceFragmentCompat 自定义布局

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:04:55 44 4
gpt4 key购买 nike

我需要为我的 PreferenceFragmentCompat 自定义布局。在 PreferenceFragmentCompat 的文档中看来您可以在 onCreateView() 中膨胀并返回一个 View 。

但是 NPE 结果:-

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
at android.support.v7.preference.PreferenceFragmentCompat.bindPreferences(PreferenceFragmentCompat.java:511)
at android.support.v7.preference.PreferenceFragmentCompat.onActivityCreated(PreferenceFragmentCompat.java:316)
at com.cls.example.MyPrefFrag.onActivityCreated(MyPrefFrag.java:42)

在我检查了 PreferenceFragmentCompat:onCreateView 的来源后,我发现了以下代码:-

 RecyclerView listView = this.onCreateRecyclerView(themedInflater, listContainer, savedInstanceState);
if(listView == null) {
throw new RuntimeException("Could not create RecyclerView");
} else {
this.mList = listView; //problem
...
return view;
}

因此,如果您覆盖 onCreateView() 并返回自定义布局,则不会调用 onCreateRecyclerView() 并且不会设置 RecyclerView 私有(private)字段 mList。因此 setAdapter() 上的 NPE 结果。

我是否应该假设自定义布局对于 PreferenceFragmentCompat 不可行?

最佳答案

您可以在主题中指定自定义布局。

例如:

styles.xml

<style name="YourTheme" parent="Theme.AppCompat">
<!-- ... -->
<item name="preferenceTheme">@style/YourTheme.PreferenceThemeOverlay</item>
</style>

<style name="YourTheme.PreferenceThemeOverlay" parent="@style/PreferenceThemeOverlay">
<item name="android:layout">@layout/fragment_your_preferences</item>
</style>

fragment_your_preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.Toolbar
android:id="@+id/custom_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<!-- Required ViewGroup for PreferenceFragmentCompat -->
<FrameLayout
android:id="@android:id/list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</FrameLayout>

</LinearLayout>

然后在 fragment 类的 onViewCreated() 中,您可以开始使用 View :

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);

Toolbar toolbar = (Toolbar)view.findViewById(R.id.custom_toolbar);

if (toolbar != null)
{
getMainActivity().setSupportActionBar(toolbar);
}
}

关于android - PreferenceFragmentCompat 自定义布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966844/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com