0

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

enter image description here

Alexa289
  • 8,089
  • 10
  • 74
  • 178

2 Answers2

2

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

}
Alexa289
  • 8,089
  • 10
  • 74
  • 178
  • This is also needed if you have multi-module project. But you need to have navigation in one separate module holding nav_graphs that are visible to each other. – Beemo May 09 '23 at 11:38
-1

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.

Sarthak Dhami
  • 330
  • 1
  • 5
  • 14