本文介绍了如果使用导航组件在每个片段中设置工具栏,如何删除顶层片段工具栏中的后退按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图阅读

解决方案

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



以便在我的 HomeFragment SearchFragment 中,您应该这样

  val工具栏= 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(工具栏,navHostFragment,appBarConfiguration)

要使用 AppBarConfiguration 类,您需要 navigation-ui-ktx 工件,并且在gradle应用中,还需要使用此编译选项和kotlin选项

  android {


compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion .VERSION_1_8
}

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

}


I have tried to read this but my problem is little bit different.

I need some different toolbars, so according the documentation from here , I need to set the toolbar in each of my fragment not in my MainActivity.

so I set the toolbar in each xml of my fragment. and then in each fragment I use this code to set the toolbar

    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)


    }

but I have back button in top level fragment of my bottom navigation view like the image below. I am confused how to pass appBarConfiguration if I set the toolbar from my fragment not from my MainActivity

解决方案

I finally get the answer. I need to set appBarConfiguration in EACH top level fragment

so in my HomeFragment and in SearchFragment, you should it like this

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)

to use AppBarConfiguration class , you need navigation-ui-ktx artifact and also in gradle app you use pass this compile options and kotlin options

android {


    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

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

}

这篇关于如果使用导航组件在每个片段中设置工具栏,如何删除顶层片段工具栏中的后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:02