Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional back navigation with Android Navigation Component

Im making navigation in my app using navigation component from jetpack. I have 3 screens in my app, all of them implemented via Fragment:
- search screen
- list screen
- detail screen

When user presses search (on search screen), app navigates to list screen loads results and displays them. User selects one of the results and navigates to detail screen. If there is only one result, app navigates from list screen to detail screen automatically, effectively skipping list screen.

The problem is back navigation: when there was multiple results I need to navigate back to list screen, but if there was only one result I need to navigate back to search screen. I want just call navigateUp, but this will take me to list screen (in all cases) and then forward to detail screen if there is only one result.

When using FragmentTransaction directly, we can replace current fragment with and call addToBackStack only if we want to return to it later. When using navigation component we can just navigate, and it behaves as replace + addToBackStack.

How can I achieve replace-without-adding-to-backstack behavior using architecture component?

like image 462
dhabensky Avatar asked Nov 29 '18 15:11

dhabensky


1 Answers

Finally, I managed how to achieve it. Now I have two actions with the same start and destination, their only difference is popUpTo attribute.

<action
    android:id="@+id/action_listFragment_to_detailFragement"
    app:destination="@id/detailFragment"/>

<action
    android:id="@+id/action_listFragment_to_detailFragement_pop"
    app:destination="@id/detailFragment"
    app:popUpTo="@id/listFragment"
    app:popUpToInclusive="true" />

action_listFragment_to_detailFragement is used when user manually performes transition and it should return to list screen later

action_listFragment_to_detailFragement_pop is used when transition performed automatically and list screen should not be shown after return.

like image 177
dhabensky Avatar answered Sep 22 '22 12:09

dhabensky