WISHY
WISHY

Reputation: 11999

Handle navigation stack in NavController navigation graph android?

There is a settings button on toolbar which opens a fragment containing list of options to open further fragments.

Settings page has 2 options

User can navigate to any of the pages, and toolbar is visible to user across every page

If I click Profile -> Profile fragment is launched -> Then I click settings on toolbar -> Settings page is launched

Now when I press back I am redirected to Profile Fragment which I don't want to happen. It should redirect to the last page visited before Settings fragment as Profile and password fragment are sub fragments for Settings fragment

This is my navigation graph for settings fragment flow

 <fragment
    android:id="@+id/settingsFragment"
    android:name="com.mountmeru.view.settings.SettingsFragment"
    android:label="fragment_settings"
    tools:layout="@layout/fragment_settings">
    <action
        android:id="@+id/action_settingsFragment_to_profileFragment"
        app:destination="@id/profileFragment" />
    <action
        android:id="@+id/action_settingsFragment_to_resetPasswordFragment"
        app:destination="@id/resetPasswordFragment" />
</fragment>

This is how I am navigate to profile and password fragment

 view.findNavController().navigate(
        R.id.action_settingsFragment_to_profileFragment)

 view.findNavController().navigate(
        R.id.action_settingsFragment_to_resetPasswordFragment)

Upvotes: 0

Views: 553

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364576

In the navigation graph in the ProfileFragment you can use:

<fragment
    android:id="@+id/profileFragment"            
    ...>

    <action
        android:id="@+id/action_profileFragment_to_settingsFragment"
        app:destination="@+id/settingsFragment"
        app:popUpTo="@id/profileFragment"
        app:popUpToInclusive="true" />

</fragment>

You can find more info about popUpTo and pupUpToInclusive here.

You can also do it in the code (without changing the nav graph):

findNavController()
        .navigate(R.id.action_profileFragment_to_settingsFragment,
                null,
                NavOptions.Builder()
                    .setPopUpTo(R.id.profileFragment,
                     true).build()
        )

Upvotes: 0

Related Questions