Navigation Component Usage

What is Navigation Component and How to Use It?

Adile Güngör ♾️ 🌎
Women in Technology
10 min readAug 26, 2023

--

Click for the Turkish version!👇:

Hello! I am Adile Güngör, one of the participants of Android Programming Academy with Kotlin. Android Programming Academy with Kotlin is carried out with the grant support provided within the scope of the “Empowerment and Access to Employment of Software Developer Youth Affected by Disaster Project”,Sivil Toplum için Destek Vakfı” and “Turkey Mozaik Foundation”.

Photo by Mitchel Willem Jacob Anneveldt on Unsplash

Today we will talk about using Navigation Component. Please check the terms related to Navigation Component at the end of the page. Please check out my footnotes too! Let’s start😊😊. Navigation Component is a tool used in Android applications, it makes it easier for the application to navigate between different “screens” or “pages”. Let’s give an example👇:

👀Suppose you are developing a car app. The app includes modules for the user to view the car gallery, view car details and buy a car. The Home Page is the entry point of the app and welcomes the user. From here you can navigate to different areas. Gallery is a place where the user can see different car models. Here the user can select a car and go to the details of the selected car with the Navigation Component. Detail, when a car is selected, this page shows the specifications, pictures and other details of the car. Buy, if a user wants to buy a car, he is redirected to this page. Navigation Component provides a space for the user to enter the necessary information. Go Back: When the user presses the back button while navigating a page, the Navigation Component follows the transition and takes the user back to the previous page.

Navigation GIF By NEEEU Spaces GmbH

The Navigation Component provides transitions between these pages. This makes the application clearer and more understandable.
It is also possible to use animations when switching between pages. For example, it is possible to add animations such as scrolling, fading, growing, etc. when moving from one page to another.

Now let’s learn starting from the first step!

Adding the Dependency: To use the Navigation Component in your project, you must add the necessary dependencies in your Gradle file👇.

⚠️Note: A dependency is the need of one piece of software on another piece of software. In Android projects, dependencies can come in the form of external libraries or modules. Dependencies are used to extend your project’s features, add additional functionality, or solve specific problems. For example, the libraries required to use the Navigation Component are dependencies. These libraries bring additional functions and capabilities to your project.

These dependencies are the libraries that are required for you to use the Navigation Component.

2.Create the Navigation File
Go to the res folder, right click and select Android Resource Directory from new. Then create a folder called navigation by selecting navigation from the value options👇. (Please read my article “Android Studio Basics” to see what these folders are for in Android Studio).

⚠️Note: A navigation graph is an XML file that describes the different screens (fragments) in your application and the transitions between them. The navigation file determines which screens users can navigate to, how the transitions will happen, and the data that will be moved during these transitions. This file allows you to manage the navigation of the application from a central location.

For this project, you can organize UI components using different layout types such as LinearLayout, RelativeLayout, ConstraintLayout.

⚠️Note: Here is a small footnote about layouts. A layout is an XML file that defines how the user interface will look and be organized. Layout files contain UI components and information about how to place, size and format them.

Create an XML file called main_activity_nav.xml under the res folder:

3. Create Fragments and Layouts
Create fragments that represent each screen in your project. Go to app>src>main>java>com>example, select Fragment and then select Blank Fragment 👇: (For example, HomePageFragment, DetailFragment, and OutputFragment).

Related layout files will also be created for these fragments.

⚠️Note: At this point we can talk about what a fragment is. A fragment is an Android component that represents a part of a user interface and has its own lifecycle. Fragments are used within activities, allowing us to create larger and more flexible user interfaces. For example, the content of a page or the content of a dialog box can be contained within a fragment. A fragment can contain UI components and manage its own behavior.

4. Define the Navigation Graph
Open main_activity_nav.xml file and define the fragments you created here. You can easily add them by clicking the add(+) button in this section.

We add the fragments. We provide connections with arrows (action) as shown in the figure:

giphy by freecodecamp

Of course it is not finished. Let’s tell our code how it will work. For this we need to add the following plugin (Safe Args, details at the end of the page)

In the Build gradle app section, we will need to add the following extension (Build.gradle is an important file used to manage the configuration and dependencies of the Android project).

The section of ⚠️Note: build.gradle in the app module is used to determine the build and runtime behavior of the app module.

In your code, make sure that android.nonTransitiveRClass=true in gradle.properties is true.
In the required fragments, for example in the detail page, you need to add arguments to pull data from the user👇:

⚠️note: An argument is the data or value required for a function or component to work. In Android, arguments are often used to move data between fragments or activities. For example, when you want to send a string or an object when moving from one fragment to another, you can carry that data as an argument.
When using the Navigation Component, arguments are used to pass data between fragments or to carry parameters during transitions. For example, arguments can be used to move data such as a user’s name, age from one fragment to another. This data can be retrieved and used in the target fragment.
Arguments are usually specified when switching from fragment to fragment in the navigation graph. For example, they can be defined in the action of a transition and arguments are passed during this action. The target fragment can then take these arguments and behave accordingly.

The Navigation Component provides special argument classes for receiving and using arguments. These classes help you to receive and use arguments in a type-safe way. For example, the DetailFragmentArgs class is defined in your project, and thanks to this class you can get arguments that are carried during the transition to DetailFragment.

This is also where we specify screen transitions and arguments to be moved. For example👇:

5. Let’s Set Transitions Between Fragments:
Use the navigation provided by the Navigation Component in your fragment classes to perform transitions between fragments. For example, when clicking a button, switch to another fragment👇:

6. Receive and Use Arguments:
You can retrieve and use the arguments you carry during migration in the target fragment. For example DetailFragment👇:

⚠️note: At this point, I can hear you saying what is a bundle 🤔 Bundle is a data structure used for moving and storing data on the Android platform. In particular, it is used to pass data between different components (activities, fragments) or to temporarily store data. Bundle works in the form of key-value pairs and supports many data types.
In Android, moving data between components such as activities or fragments is usually done through mechanisms such as Intents or Fragment Arguments. Bundle refers to the data structure that holds the key-value pairs used in these mechanisms.
For example, imagine you want to move a text string from one activity to another.

In this case, you can create a Bundle and move this data as a key-value:
So what does this code☝️ do?
With this code, we process arguments from the Android Jetpack Navigation Component

val bundle: DetailFragmentArgs by navArgs(): This line defines a property called bundle to receive arguments to the fragment. DetailFragmentArgs is a helper class that facilitates the handling and processing of arguments. This usage automatically manages how arguments are passed to and received from the fragment.
val gelenAd= bundle.ad: This line assigns the argument named name in the bundle to a variable named incomingAd. This way you can use the name data passed to the fragment. This also applies to the age, last name and object arguments.

Navigation Component can work integrated with components like avigationView, AppBarConfiguration. This way you can manage screen transitions and ActionBar. I think each topic I mentioned can be the subject of a separate article. It is possible that I will surprise you 😉 !
By following these steps, you can start using the Navigation Component in your project. This will make your application’s screen transitions more organized and manageable, and will also make it easier to move data between fragments. Here is the GitHub link of my project with the codes I have explained here👆!

Hadi Tok, whom I love to follow, met thanks to the academy and now receive mentoring, has prepared a very nice series for us. I am leaving his last series here. He also recommends us to use navigation component😊. I hope this article will remove the question marks in your mind. Please read it:

Some Terms About Navigation Component and Their Meanings:
I added a picture on each term because I wanted you to relate the terms and pictures. I did:) Enjoy the analogies!

Photo by Jackie Park on Unsplash
  • NavHostFragment and NavHostActivity: NavHostFragment or NavHostActivity is used to direct navigation operations and determine which area is the area where navigation takes place
Photo by Rob Laughter on Unsplash
  • Transition Animations: The Navigation Component makes it easy to add transition animations when managing screen transitions. You can use transition animations to determine how screens appear and scroll during transitions.
Photo by Anastasia Zhenina on Unsplash
  • Back Stack and Back Key Behavior: Navigation Component does back stack management automatically. However, sometimes you may need to backstack fragments back key or programmatically. Understanding this behavior allows you to better control your navigation.
Photo by Andrew Dunstan on Unsplash
  • Using Safe Args: The Navigation Component provides the Safe Args mechanism that allows you to pass arguments in a type-safe manner. This mechanism ensures safe and consistent passing of data.
Photo by Aleksandr Popov on Unsplash
  • Fragment Lifecycle and Data Loss: Understanding the fragment lifecycle is important to avoid data loss in case fragments are rebuilt. It is necessary to understand how to protect arguments and data.
Photo by Alex Haney on Unsplash
  • NavigationUI and ActionBar: NavigationUI allows you to synchronize the ActionBar with fragment transitions. This makes the UI more consistent and user-friendly.
Photo by Mark König on Unsplash
  • Deep Linking: With the Navigation Component you can create deep linking. This allows you to respond to requests from external sources (e.g. web URLs) and provide direct access to specific screens.
Photo by Phil on Unsplash
  • Bottom Navigation or Drawer Menu Integration: You can integrate different navigation structures (e.g. bottom navigation bar or scrollable menu) with the Navigation Component. This can help improve the user experience.
Photo by Krzysztof Kowalik on Unsplash
  • Data Migration Methods: Apart from arguments, you can also use data migration methods using ViewModel. ViewModel helps to share data between fragments in a secure and consistent way.

Thank you for reading. Have a good week and I will be sharing screenshots from my project with you, please stay tuned😉!
If you wish, you can check out my GitHub and Linkedin profile. And you can send your questions. Thanks❤️.

Stop! If you are looking for a youTube video recommendation for Kotlin, KEKOD is good for you👇!

--

--