Hey developers out there, I am here with another article for the series “Navigation in Multi-page Apps”. If you are new to this series, please read the previous articles.
Navigation in Multi-page Apps | Part 1
So let’s begin. In the previous article, we discussed the first way to create multiple pages and navigation mechanisms. But in the Jetpack way, we use some of the new Jetpack libraries. Here we use Fragments instead of Activities as pages and Navigation component library as a way to navigate.
Note: But to host fragments we need one Activity. We will use the default Activity as a Host activity.
You can always refer to the final code which is published here: Android Multipage Sample | Github
Jetpack way
First things first, add the required dependencies
Now create the fragments.
Right-click the package name and New -> Fragments -> Blank Fragment
Do that twice and name each NavFirstFragment and NavSecondFragment respectively. Remove some boilerplate code.
Earlier I said that we need an Activity to host these fragments. So inside the activity_main.xml add a FragmentContainerView as a container to hold these fragments.
Here you noticed that we added new attributes such as app:defaultNavHost and app:navGraph.
defaultNavHost is set to true such that this activity knows this is the primary Fragment Container.
What do I actually mean by that?
One Activity can contain/host multiple Fragment Containers. So to make one primary we have to set it to true.
Another question arises, why do we need a primary Fragment Container?
Sometimes you need to capture app-level events and manipulate app-level UI.
Events I mean here is Back button clicks and UI I mean for Action bar title text.
As a rule of thumb, always set one host as primary.
Next question, what is this navGraph thing?…
This is the beauty of the Navigation Component. Instead of programmatically launching new pages like in the Traditional way, we declare the Navigation and Actions in an XML file.
If you copy-pasted the above code, you will get an error in IDE as no such resource. Our next step is to create that file.
Right-click res folder New -> Android Resource File
Then type the XML file name, then click OK.
Open that XML file and in the design section, you have to add the two fragments you created previously.
Click that add destination Icon to add fragments.
Then add these little cute arrows from the First fragment to the second fragment. These are the actions or navigation for our app.
So we are done?? NO… one small thing you have to do to make it work.
What is that? Calling these actions in our code : )
Add a button in fragment_nav_first.xml file and add a click Listener to it in NavFirstFragment.kt
Now we are done : )
Thank you for reading my articles. Please leave a comment if you have any issues with that. In upcoming articles, we will discuss how we can pass data between pages.
Documentation: Navigation | Android Developers
Follow me on Twitter
Happy coding : )