Android Navigation Component is a part of the Android Jetpack library that simplifies the implementation of navigation in Android applications. It provides a framework for navigating between different screens or destinations within an application.
To use Navigation Component in a Kotlin-based Android app, you need to add the Navigation dependency in the app-level build.gradle file.
dependencies {
def nav_version = "2.3.5"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}
After adding the dependency, you can create a navigation graph file in the res/navigation directory. The navigation graph file defines the different destinations and the routes between them.
You can then define a NavHostFragment in your activity layout file. The NavHostFragment acts as a container for the fragments that will be navigated to.
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
To navigate to a destination, you can use the NavController class to get the instance of the NavHostFragment and call the navigate() method with the destination ID.
val navController = findNavController(R.id.nav_host_fragment)
navController.navigate(R.id.destination_id)
Navigation Component simplifies the implementation of navigation in Android applications by providing a framework for navigating between different screens or destinations within an application. With the help of Navigation Component, developers can easily manage navigation and reduce boilerplate code.