首页 > 解决方案 > 如果我使用导航组件在每个片段中设置工具栏,如何删除顶级片段工具栏中的后退按钮?

问题描述

我试过读这个,但我的问题有点不同。

我需要一些不同的工具栏,因此根据此处的文档,我需要在我的每个片段中设置工具栏,而不是在我的 MainActivity 中。

所以我在片段的每个 xml 中设置了工具栏。然后在每个片段中我使用这段代码来设置工具栏

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val toolbar = view.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar3)

        val navHostFragment = NavHostFragment.findNavController(this);
        NavigationUI.setupWithNavController(toolbar, navHostFragment)


    }

但我在底部导航视图的顶级片段中有返回按钮,如下图所示。如果我从我的片段而不是我的 MainActivity 设置工具栏,我很困惑如何传递 appBarConfiguration

在此处输入图像描述

标签: androidandroid-architecture-componentsandroid-jetpackandroid-architecture-navigationandroid-jetpack-navigation

解决方案


我终于得到了答案。我需要appBarConfiguration在每个顶级片段中设置

所以在 myHomeFragment和 in 中SearchFragment,你应该这样

val toolbar = view.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar2)
val appBarConfiguration = AppBarConfiguration(setOf(
    R.id.destination_home,
    R.id.destination_search)
)

val navHostFragment = NavHostFragment.findNavController(this);
NavigationUI.setupWithNavController(toolbar, navHostFragment,appBarConfiguration)

要使用AppBarConfigurationclass ,您需要navigation-ui-ktxartifact 并且在您使用的 gradle 应用程序中传递此编译选项和 kotlin 选项

android {


    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

}

推荐阅读