Android-PreferenceFragmentCompat添加Toolbar

PreferenceFragmentCompatonCreateView 里面引用的布局资源 R.layout.preference_list_fragment 根布局是 LinearLayoutandroid:orientationvertical

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="NewApi"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >

    <FrameLayout
        android:id="@android:id/list_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp"
        android:gravity="center"
        android:visibility="gone" />

</LinearLayout>

只需要在0的位置添加一个ChildView。

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = super.onCreateView(inflater, container, savedInstanceState)
        if (view is LinearLayout) {
            // AppBar
            val appbar = LayoutInflater.from(context).inflate(R.layout.settings_appbar, null)
            val toolbar = appbar.findViewById<MaterialToolbar>(R.id.tool_bar)
            Util.setToolbarDefaultConfig(toolbar, R.string.settings)
            toolbar.setNavigationOnClickListener {
                findNavController().popBackStack()
            }
            view.addView(appbar, 0)
        }
        return view
    }

你可能感兴趣的:(Android)