A Navigation host is a container that we place in our app. We use this container to display the active fragment or activity for our current destination.
The Navigation controller is an object that we create in code to control the navigation between the destinations in the navigation component.
The Navigation graph is the actual visual representation of how our navigation will work and look.
For the latest version, visit the android navigation library page.
Also, keep in mind that you will need Android Studio 3.3. or higher and Java 8 to use the navigation component feature.
Creating the Navigation Graph
First, create the navigation graph.
Give the file a name and change the resource type to Navigation.
Creating the Navigation Host
Next, create the Navigation Host.
I am using the Constraint Layout, so I need to add the constraints for the navigation host fragment. If you are using a different layout, make sure to set the parameters for the host so it will be visible.
Now that we have our container to place our fragments and activities in and a graph to map out our application, we can start creating the destinations.
Go back to the navigation graph. Click on the New Destination icon and then "Create New destination. "
Select a fragment layout and click next. Rename the fragment and click finish
Using and Existing Fragment
If you have an existing fragment or activity that you want to add, add a placeholder.
Changing the Fragment Layout
Instead of using the default blank layout, I will replace the text view widget with a button. I will do that to both of the fragments so we can tell the difference between the two.
To navigation between the destinations, we will have to do it in the code. Go to the start destination’s fragment class file.
If you have an error, you may need to import the Navigation class.
If we run the application now and click on the button, it will transition to another destination.
The last thing I want to mention in this video for the Navigation component is Actions. An Action is the link between 2 destinations. They are used to determine the behavior when the component makes a transition from one destination to another.
It will create an arrow between the 2 destinations. If we click on the arrow, we can see that it has an id and some other attributes.
If we run the application, we will get the same effect.
©2019 - 2023 Codeible. All rights reserved.