Search code examples
androidandroid-jetpackandroid-jetpack-navigation

How to close All fragments with activity programmatically using Jetpack navigation


enter image description here

Here is scenario:

  1. On login activity button click open Activity 2
  2. In Activity 2 multiple fragments and navigate through navgraph
  3. I want to go back on login screen while click on Fragment 3 Finish button

Here what I try but no luck:

findNavController().navigate(
                R.id.action_fragment3_to_fragment1,
                null,
                NavOptions.Builder()
                    .setPopUpTo(R.id.fragment1, true).build())

Solution

  • You need to close Activity 2 using finish() and the fragments will be closed with the activity, to close Activity 2 from Fragment 3 you can use this line of code inside Fragment 3:

    requireActivity().finish()