Search code examples
androidandroid-fragmentsandroid-architecture-navigation

backstack does not clear while navigating from fragment to activity


Here is my code

<fragment
  android:id="@+id/fragment1"
  android:name="com.example.app.Fragment1"
  android:label="SignatureFragment"
  tools:layout="@layout/layout_fragment1">
    <action
      android:id="@+id/action_fragment1_to_main_activity"
      app:destination="@id/main_activity"
      app:enterAnim="@anim/slide_in_from_right"
      app:exitAnim="@anim/no_anim"
      app:launchSingleTop="true"
      app:popEnterAnim="@anim/no_anim"
      app:popExitAnim="@anim/slide_out_to_right"
      app:popUpTo="@id/navigation_graph_id"
      app:popUpToInclusive="true" />
</fragment>

<activity
  android:id="@+id/main_activity"
  android:name="com.example.app.MainActivity"
  android:label="MainActivity"
  tools:layout="@layout/activity_main" />

Now the code for navigation

findNavController().navigate(R.id.action_fragment1_to_main_activity)

When I navigate to activity and press back, the fragment is still there. I want to clear the backstack after opening the activity.

I tried to remove the animation and also tried with removing app:launchSingleTop, but no success.


Solution

  • Edit Jetpack Navigation is intended to work with single activity and does not fully support activity navigation with parameters passed to actions

    Thus to clear stack when navigating from one activity to another you will still need to call activity.finish()

    Edit end

    The thing is findNavController().navigate(R.id.action_fragment1_to_main_activity) wont work.

    Try to navigate via navigate(@NonNull NavDirections directions). In your case it will look something like this

    findNavController().navigate(
         Fragment1Directions.actionFragment1ToMainActivity())
    

    Hope it helps.