how to remove back button in the toolbar of top level fragment if I set toolbar in each fragment using navigation component?

混江龙づ霸主 提交于 2020-04-17 21:58:48

问题


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


回答1:


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

}



回答2:


You should try the CUSTOM ACTION BAR instead default ACTION BAR and In which fragment you don't want to back Button Just set VISIBILITY GONE.



来源:https://stackoverflow.com/questions/61093359/how-to-remove-back-button-in-the-toolbar-of-top-level-fragment-if-i-set-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!