How To Navigate To A Destination From Any Fragment Using The Navigation Architecture Component in Android
When using a single activity architecture pattern in an android project and you happen to have many fragments and then there's a particular fragment which you want to be able to navigate to from any part of the screens or from any destination on the NavGraph you can come up with different ways of making this work, some of the solutions may scale and may not.
Let's Get Started
Navigating to a particular destination from any Fragment in a NavGraph is pretty you. You start by opening your navigation.xml file and locate the "Add action" button (a forward-facing arrow) and click to open a menu like the one in the image below:
And here is what menu that will be shown to you looks like
if you look closely you will see fields like ID, From and Destination
the From field has been automatically selected, in our case it is navigation which means the action request is coming from every destination on the graph.
Select the Destination you want to navigate to and it will generate an ID for you to reference when needed after this go ahead and set Transition and the Pop Behaviour as you like and then click on "Add" to finish
Below is what the menu should look like when you're done adding your input
Notice the ID Generated? Yeah, you are following.
To confirm if what we've been doing so far is actually working find the fragment which you set as Destination you'd notice a new arrow icon appended to the start of the Fragment
In this example, I used a CartFragment as my destination and you can see the circled icon.
Almost Done
Now we are almost done here. To make use of this action you can call it anywhere in your code
cart.setOnClickListener {
findNavController().navigate(R.id.action_global_cartFragment)
}
And that's all.
You can also edit the attributes of the is action by clicking on the icon appended to the Fragment and it will show you all the action's attribute on the right side of the editor
Now we are done.
"Those who know how to learn... know enough." - Henry Adams
Happy Coding!