I'm trying to use the Android Jetpack Settings guide with a toolbar. The guide says that the root tag to be <PreferencesScreen>, so I can not include the toolbar in the xml. I'm using a NoActionBar theme. According to the Android Jetpack guide for support app bar variations it is advised to remove the top bar from the activity and instead define it in each destination fragment. So I have the following files:
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreferenceCompat
app:key="notifications"
app:title="Enable message notifications" />
<Preference
app:key="feedback"
app:summary="Report technical issues or suggest new features"
app:title="Send feedback" />
</PreferenceScreen>
SettingsFragment.kt
class SettingsFragment: PreferenceFragmentCompat(){
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
}
Everything runs fine, and the settingsFragments opens well, but because I do use the NoActionBar theme it seems like there is not way for me to add the toolbar without defining it in the main_activity. Is my assessment correct, or is there a way for me to add a custom toolbar afterall to the preference fragment?
Maybe it's too late but you can achieve it in this way ->
<style name="PrefsTheme" parent="PreferenceThemeOverlay.v14.Material">
<item name="android:layout">@layout/fragment_settings</item>
</style>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/item_toolbar" />
<!-- the id is defined by the support lib. -->
<FrameLayout
android:id="@android:id/list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:targetApi="n" />
</LinearLayout>
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="preferenceTheme">@style/PrefsTheme</item>
</style>
Then in your SettingsFragment you can find toolbar by id and make all customizations to it:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Toolbar>(R.id.toolbar)?.let {
// Customize toolbar
}
}