Navigation Between Fragments

This is my note for Udemy lesson: Advanced Android Bootcamp 2024.

1. Add Dependencies

Reference
In project layer's build.gradle.kts:

buildscript {
  ...
  dependencies {
    val nav_version = "2.7.7"
    classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
  }
}

In app layer's build.gradle.kts:

dependencies {
  val nav_version = "2.5.3"
  implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
  implementation("androidx.navigation:navigation-ui-ktx:$nav_version")
}

2. Create a Navigation Graph File

Highlight app folder -> File -> New -> Android Resource File -> Input file name like "nav_graph" -> Change resource type to "Navigation"

3. Add NavHostFragment

  1. Open activity_main.xml, switch to design mode.
  2. Find "NavHostFragment" from Palette's Containers group, drag it to screen.
  3. A popup will show to ask which navigation graph it links to, choose the one just created(nav_graph.xml).

4. Create Fragments

  1. Open nav_graph.xml.
  2. Click the icon "New Destination" -> Create new destination -> Fragment(Blank)
  3. Edit fragment name and press "Finish" button.
  4. Repeat the step to create another fragment.

5. Create Navigation Acton

  1. Open nav_graph.xml
  2. Drag a line from one fragment to another, an action will be automatically created. Assume the two fragments are HomeFragment and SecondFragment, the created action will be action_homeFragment_to_secondFragment.
  3. Select the action(which displays as an arrow), we can set its animations in the attributes window.

6. Use the Navigation Action

First, create a button in HomeFragment, then in its onCreateView function, write the following code:

xxxButton.setOnClickListener {
  it.findNavController().navigate(R.id.action_homeFragment_to_secondFragment)
}