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
- Open
activity_main.xml
, switch to design mode. - Find "NavHostFragment" from Palette's Containers group, drag it to screen.
- A popup will show to ask which navigation graph it links to, choose the one just created(
nav_graph.xml
).
4. Create Fragments
- Open
nav_graph.xml
. - Click the icon "New Destination" -> Create new destination -> Fragment(Blank)
- Edit fragment name and press "Finish" button.
- Repeat the step to create another fragment.
5. Create Navigation Acton
- Open
nav_graph.xml
- Drag a line from one fragment to another, an action will be automatically created. Assume the two fragments are
HomeFragment
andSecondFragment
, the created action will beaction_homeFragment_to_secondFragment
. - 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) }