0
0
Android Kotlinmobile~5 mins

Why navigation manages app flow in Android Kotlin

Choose your learning style9 modes available
Introduction

Navigation helps users move between different screens in an app smoothly. It keeps the app organized and easy to use.

When you want to move from a home screen to a details screen.
When users need to go back to a previous screen after completing a task.
When your app has multiple sections like settings, profile, and messages.
When you want to show a new screen after a button click.
When you want to control the order of screens users see.
Syntax
Android Kotlin
val navController = findNavController(R.id.nav_host_fragment)
navController.navigate(R.id.destinationFragment)
Use findNavController to get the navigation controller from your fragment or activity.
Call navigate() with the ID of the destination to move to that screen.
Examples
This moves the user to the profile screen.
Android Kotlin
val navController = findNavController(R.id.nav_host_fragment)
navController.navigate(R.id.profileFragment)
Navigate to the settings screen from the current screen.
Android Kotlin
navController.navigate(R.id.settingsFragment)
This takes the user back to the previous screen.
Android Kotlin
navController.popBackStack()
Sample App

This simple app has a button on the main screen. When you tap it, the app moves to the second screen using navigation.

Android Kotlin
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val navController = findNavController(R.id.nav_host_fragment)

    findViewById<Button>(R.id.buttonToSecond).setOnClickListener {
      navController.navigate(R.id.secondFragment)
    }
  }
}
OutputSuccess
Important Notes

Navigation helps keep track of where the user is in the app.

It makes it easy to handle the back button correctly.

Using navigation reduces code complexity by managing screen changes for you.

Summary

Navigation controls how users move between screens.

It makes apps easier to use and understand.

Use navigation to keep your app flow smooth and organized.