Stop fragment refresh in bottom nav using navhost

后端 未结 8 1727
夕颜
夕颜 2020-12-31 12:14

This problem has been asked a few times now, but we are in 2020 now, did anyone find a good usable solution to this yet?

I want to be able to navigate using the bott

8条回答
  •  悲&欢浪女
    2020-12-31 12:41

    Kotlin 2020 Google's Recommended Solution

    Many of these solutions call the Fragment constructor in the Main Activity. However, following Google's recommended pattern, this is not needed.

    Setup Navigation Graph Tabs

    Firstly create a navigation graph xml for each of your tabs under the res/navigation directory.

    Filename: tab0.xml

    
    
    
        
        
    
    

    Repeat the above template for your other tabs. Important all fragments and the navigation graph has an id (e.g. @+id/tab0, @+id/fragmentA).

    Setup Bottom Navigation View

    Ensure the navigation ids are the same as the ones specified on the bottom menu xml.

    
    
    
        
    
        
    
        
    
        
    
    
    

    Setup Activity Main XML

    Ensure FragmentContainerView is being used and not and do not set the app:navGraph attribute. This will set later in code

    
    
    

    Main Activity XML

    Copy over the following Code into your main activity Kotlin file and call setupBottomNavigationBar within OnCreateView. Ensure you navGraphIds use R.navigation.whatever and not R.id.whatever

    private lateinit var currentNavController: LiveData
    
    private fun setupBottomNavigationBar() {
      val bottomNavigationView = findViewById(R.id.bottomNavigationView)
      val navGraphIds = listOf(R.navigation.tab0, R.navigation.tab1, R.navigation.tab2, R.navigation.tab3)
      val controller = bottomNavigationView.setupWithNavController(
          navGraphIds = navGraphIds,
          fragmentManager = supportFragmentManager,
          containerId = R.id.fragmentContainerView,
          intent = intent
      )
      controller.observe(this, { navController ->
          val toolbar = findViewById(R.id.main_toolbar)
          val appBarConfiguration = AppBarConfiguration(navGraphIds.toSet())
          NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)
          setSupportActionBar(toolbar)
      })
      currentNavController = controller
    }
    
    override fun onSupportNavigateUp(): Boolean {
      return currentNavController?.value?.navigateUp() ?: false
    }
    

    Copy NavigationExtensions.kt File

    Copy the following file to your codebase

    Source

    • Google's Solution

提交回复
热议问题