- Published on
Android Jetpack Navigation: Essential Knowledge
- Authors
- Name
- Dan Tech
- @dan_0xff
Every Android application will contain many screens. Navigating between screens needs to be managed carefully, and it must be easy for developers. Jetpack Navigation was created for this purpose. Some features of Jetpack Navigation will help you develop applications faster.
Knowledge required before learning this part: Android Activity Lifecycle, Android View System
- Define Fragments and the links between them in advance through Navigation Id
- Customize Navigation to a specific Fragment using the Deep-link feature
- Support managing Fragment Back Stack (support multiple backstack) in Activity (extremely useful)
This article will guide you on integrating the Jetpack Navigation Component into your project and using it easily!
GitHub Repository: https://github.com/dantech0xff/SpotifyKt
Add Nav Graph to Activity
// Jetpack Nav
// Add dependencies to build.gradle module app
implementation("androidx.navigation:navigation-fragment-ktx:2.7.7")
implementation("androidx.navigation:navigation-ui-ktx:2.7.7")
// Add NavHostFragment to your Activity
// Create Fragments and set them up in the mobile_navigation.xml file
For each Fragment you create, you need to create a fragment inside mobile_navigation as well.
To create a navigation link between two fragments, you can drag and drop within the Visualize Panel, and the code will be generated as below.
You can also navigate to a Fragment by defining a deep-link for it.
// declare deeplink for deeplink navigation
// To perform navigation according to a Nav Id, you can call it in the project as follows
findNavController()
.navigate(R.id.action_navigation_search_to_searchResultFragment)
// To perform navigation according to a Nav Deep-link, you can call it in the project as follows
fun NavController.handleDeeplinkInternal(deeplink: String?): Boolean {
return graph.hasDeepLink(android.net.Uri.parse(deeplink)).let { hasDeepLink ->
if (hasDeepLink) {
navigate(
android.net.Uri.parse(deeplink), NavOptions.Builder()
.setEnterAnim(R.anim.fade_in_anim)
.setExitAnim(R.anim.fade_out_anim)
.setPopEnterAnim(R.anim.fade_in_anim)
.setPopExitAnim(R.anim.fade_out_anim)
.build()
)
}
hasDeepLink
}
}
Basically, that's all there is to Jetpack Navigation. To effectively apply the functionalities of Jetpack Navigation, please refer to the source code here.