How to clear navigation stack after navigating to another fragment in Android

To clear the navigation stack after navigating to another fragment in Android using Kotlin, you can follow these steps:

  1. Get the NavController: Retrieve the NavController instance using the findNavController() method. This method is usually called on the View or Fragment that triggers the navigation.

  2. Navigate to the destination fragment: Use the navigate() method on the NavController instance to navigate to the desired fragment. Pass in the destination fragment's ID as an argument to this method.

  3. Clear the back stack: After navigating to the new fragment, call the popBackStack() method on the NavController instance. This method clears the navigation back stack, removing all the previous fragments from the stack.

Here's an example code snippet that demonstrates these steps:

// Step 1: Get the NavController
val navController = findNavController()

// Step 2: Navigate to the destination fragment
navController.navigate(R.id.destinationFragment)

// Step 3: Clear the back stack
navController.popBackStack()

By following these steps, you can clear the navigation stack after navigating to another fragment in Android using Kotlin. This ensures that the user cannot navigate back to the previous fragments.