Conditional back navigation with Android Navigation Component

一个人想着一个人 提交于 2020-02-21 14:15:14

问题


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?


回答1:


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.




回答2:


In Navigation Component, you can use the method NavController.popBackStack(int action) which works similar to addToBackStack(null).



来源:https://stackoverflow.com/questions/53541987/conditional-back-navigation-with-android-navigation-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!