Home > Enterprise >  How to close All fragments with activity programmatically using Jetpack navigation
How to close All fragments with activity programmatically using Jetpack navigation

Time:07-20

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())

CodePudding user response:

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()

CodePudding user response:

First, add attributes app:popUpTo='your_nav_graph_id' and app:popUpToInclusive="true" to the action tag.

<fragment
android:id="@ id/signInFragment"
android:name="com.glee.incog2.android.fragment.SignInFragment"
android:label="fragment_sign_in"
tools:layout="@layout/fragment_sign_in" >
<action
    android:id="@ id/action_signInFragment_to_usersFragment"
    app:destination="@id/usersFragment"
    app:launchSingleTop="true"
    app:popUpTo="@ id/main_nav_graph"
    app:popUpToInclusive="true" />

Second, navigate to the destination, using above action as parameter.

findNavController(fragment).navigate(
 SignInFragmentDirections.actionSignInFragmentToUserNameFragment())
  • Related