multi navGraph BottomNavigationView in navigation 2.4.0
Asked Answered
P

1

2

I have 3 tabs A, B, C in BottomNavigationView and each has a nav graph.

I can do what I want perfectly in navigation 2.3.3 by a complicated navigation extension, just like the old architecture-components-samples. This sample is now upgrade to 2.4.0. which use less code.

What I want is:

Step: Graph A' s start destination fragment A1 navigate to A2.

Step: Tap tab B or C.

  1. B or C' s navigateUp action is back to A. (works fine)
  2. When back to tab A, it shows A2. (in 2.4.0' s sample, shows A1)
  3. The BottomNavigationView' s ItemReselected action is popBackStack to current graph' s startDestination. (how to set setOnItemReselectedListener if the navController does not change?)
  4. The three startDestination fragment A1, B1, C1 are top level destinations, so B1 and C1' s toolbar do not show back icon. (works fine, because the sample set a set of these 3 fragments instead of navController.graph to AppBarConfiguration)

2.4.0 said it support Multiple back stacks. What does it mean? Can I make my BottomNavigationView in 2.4.0?

Here is how I do "3. The BottomNavigationView' s ItemReselected action..." in 2.3.3:

private fun BottomNavigationView.setupItemReselected(
    graphIdToTagMap: SparseArray<String>,
    fragmentManager: FragmentManager
) {
    setOnNavigationItemReselectedListener { item ->
        ... // get the item' s navController
        navController.popBackStack(
            navController.graph.startDestination, false
        )
    }
}

What I do in 2.4.0: just copy the sample code.

Plenteous answered 26/1, 2022 at 3:56 Comment(0)
A
1

Add setOnItemReselectedListener and popBackStack

import android.util.SparseIntArray
import androidx.core.util.getOrElse

  private val startDestinationIdByNavId: SparseIntArray by lazy(NONE) {
    SparseIntArray(5).apply {
      put(R.id.tab_home_nav, R.id.tabHomeFragment)
      put(R.id.tab_profile_nav, R.id.tabMyProfileFragment)
    }
  }

  fun setupViews() {
    binding.bottomNavView.run {
      setupWithNavController(navController)

      // Pop the back stack to the start destination of the current navController graph
      setOnItemReselectedListener {
        navController.popBackStack(
          destinationId = startDestinationIdByNavId.getOrElse(it.itemId) {
            error("Unknown menu item $it")
          },
          inclusive = false,
        )
      }
    }
  }
Autography answered 16/3, 2022 at 10:10 Comment(1)
Thanks, this fix the bug of nested graphs on bottom navigation after version 2.3.5 of navigation!Transience

© 2022 - 2024 — McMap. All rights reserved.