将工具栏添加到首选项屏幕片段

Adding a toolbar to a preferencescreen fragment

我正在尝试使用 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 来支持应用栏变体,建议从 activity 中删除顶部栏,而是在每个目的地中定义它分段。所以我有以下文件:

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)
    }
}

一切运行良好,settingsFragments 打开也很好,但因为我确实使用了 NoActionBar 主题,所以我似乎无法添加工具栏而不在 main_activity 中定义它。我的评估是否正确,或者我有没有办法将自定义工具栏添加到首选项片段?

也许为时已晚,但您可以通过这种方式实现 ->

  • 定义偏好主题:
<style name="PrefsTheme" parent="PreferenceThemeOverlay.v14.Material">
    <item name="android:layout">@layout/fragment_settings</item>
</style>
  • fragment_settings.xml:
<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>

然后在您的 SettingsFragment 中,您可以通过 ID 找到工具栏并对其进行所有自定义:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    view.findViewById<Toolbar>(R.id.toolbar)?.let {
        // Customize toolbar 
    }
}