Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destinations chaining in Android Navigation Components

I have a simple navigation graph like this:

MainFragment -> ListFragment -> DetailFragment

How can I achieve a "shortcut" from MainFragment to DetailFragment, so that:

  • UP navigation from DetailFragment will navigate to ListFragment within the graph and
  • BACK navigation from DetailFragment will return to MainFragment (optionally, BACK could behave as UP)

Is this possible? Thanks for suggestions!

EDIT: My Solution

I can simply navigate to ListFragment first and then immediately to DetailFragment like this (I call both "navigate" calls from MainFragment):

findNavController().navigate(MainFragmentDirections.toListFragment())
findNavController().navigate(ListFragmentDirections.toDetailFragment(data))

According to documentation, which says, that "... Up button should function identically to the system Back button", I decided not to make differences between BACK and UP actions.

like image 848
Berťák Avatar asked Aug 16 '26 01:08

Berťák


1 Answers

To move through fragments using the navigation components you should link them in the navigation graph, go to app-> res-> navigation-> graphName.xml (In the picture I use placeholders, use your fragments instead).

As you can see in the documentation to navigate from one fragment to another you need to use this line Navigation.findNavController(view).navigate(R.id.viewTransactionsAction); Where viewTransactionsAction should be the id of the arrow (in the graph) from one fragment to the next.

enter image description here

To override the back button action use:

@Override
public boolean onSupportNavigateUp() {
    return Navigation.findNavController(this, R.id.nav_host_fragment).navigateUp();
}

And replace inside the navigation nav_host_fragment to the arrow id of the page you want to navigate to.

like image 160
Guy Luz Avatar answered Aug 18 '26 15:08

Guy Luz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!