Move from child fragment to other child fragment from option menu

61 Views Asked by At

Hi have a navigation component with 4 destination, and I add that destination in an option menu.

It works perfectly, but now I need to move from a selected fragment to another one, but I didn't found any solution, because I can open my selected fragment, but I can't reopen the first one.

This is the configuration of nav controller in MainActivity:

val navView: NavigationView = binding.navView
navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(
    setOf(
        R.id.nav_home,
        R.id.nav_two,
        R.id.nav_three,
        R.id.nav_four
    ), drawerLayout
)

navController?.let {
    setupActionBarWithNavController(it, appBarConfiguration)
    navView.setupWithNavController(it)
}

This is the (wrong) call in second fragment to go programmatically to go to forth fragment:

requireActivity().findNavController(R.id.nav_host_fragment).navigate(R.id.nav_four)

Like I say, I go correctly to fourth fragment, but navigation not work correctly, because after that it's impossible to select home fragment selection in side menu.

Any solutions?

2

There are 2 best solutions below

1
On

Lets consider you have my_navigation.xml file, and you added 4 fragments fragment_1, fragment_2, fragment_3 and fragment_4 respectively. You should add paths between each fragment.

  • from fragment_1 to fragment_2, fragment_3, fragment_4
  • from fragment_2 to fragment_1, fragment_3, fragment_4
  • from fragment_3 to fragment_1, fragment_2, fragment_4
  • from fragment_4 to fragment_1, fragment_2, fragment_3

So, you can navigate from any fragment to any fragment with actionID.

ref: https://medium.com/swlh/android-navigation-component-part-1-6191323eaf39

from any fragment, you can navigate to another fragment like this:

findNavController().navigate(R.id.yourActionID_that_your_write_in_myNavigation_xml_file)

I might misunderstood the question, if it is, please update me. Good Luck!

0
On

I found that solution, under navigator code in main activity just add:

navView.setNavigationItemSelectedListener { item ->
    when(item.itemId) {
        R.id.nav_home -> {
            navController.navigate(R.id.nav_home)
        }
        R.id.nav_one -> {
            navController.navigate(R.id.nav_one)
        }
        R.id.nav_two -> {
            navController.navigate(R.id.nav_two)
        }
        R.id.nav_three -> {
            navController.navigate(R.id.nav_three)
        }
    }
//And if you want to close drawer
//drawerLayout.closeDrawer(GravityCompat.START)
    true
}