为PreferenceActivity添加Toolbar时遇下级页面视图找不到异常
解决PreferenceActivity添加Toolbar后子页面找不到android:id/prefs的问题
我之前也碰到过一模一样的问题,其实根源在于PreferenceActivity的子页面加载逻辑:当你进入下一级偏好设置页面时,系统默认会尝试把对应的PreferenceFragment加载到ID为android:id/prefs的容器视图里,但你的自定义布局里只放了android:id/list(用于显示顶层偏好列表),没有这个子Fragment容器,所以才会抛出找不到视图的异常。
解决方案:修改自定义布局,添加子Fragment容器
你只需要在原布局里添加一个FrameLayout,并给它设置ID为android:id/prefs,同时保留原来的ListView(android:id/list)即可。修改后的布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:title="@string/app_name" app:navigationIcon="@drawable/back" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <!-- 顶层偏好列表的容器 --> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="visible"/> <!-- 子偏好页面Fragment的容器,必须设置这个ID --> <FrameLayout android:id="@android:id/prefs" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"/> </LinearLayout>
为什么这样能解决问题?
- 当你在顶层页面时,
ListView(android:id/list)会显示你的根偏好列表,此时FrameLayout可以设为gone隐藏起来。 - 当你点击进入子偏好页面时,系统会自动把对应的
PreferencesFragmentButtonInteraction加载到android:id/prefs这个容器里,同时隐藏原来的ListView,这样就不会出现找不到视图的异常了。
额外补充:绑定Toolbar的代码
别忘了在你的PreferenceActivity的onCreate方法里绑定Toolbar并设置为ActionBar,这样Toolbar才能正常工作:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_custom_layout); // 替换成你的自定义布局文件名 Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // 如果需要返回按钮 if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } }
这样修改后,不管是顶层页面还是子页面,都能正常显示Toolbar,也不会再出现找不到android:id/prefs的错误啦。
内容的提问来源于stack exchange,提问作者theblitz
相关产品推荐
相关产品推荐

