导航组件:跳转到动态根目录并清除后退堆栈 [英] Navigation Component: jump to dynamic root destination and clear backstack

查看:96
本文介绍了导航组件:跳转到动态根目录并清除后退堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jetpack导航时,我们可以使用 popUpTo popInclusive 清除堆栈.但是,当我不知道 popUpto 的目标位置时,如何清除堆栈?

When using Jetpack Navigation, we can use popUpTo and popInclusive to clear the stack. But how do I clear the stack when I don't know what destination to popUpto?

说我有3个主要目的地,到达目的地时应该有一个清晰的栈.每个主要目的地都有自己的屏幕流(可以通过深层链接直接访问).

Say I have 3 main destinations that should have a clear stack when we arrive at them. And each main destination has its own flow of screens (which can be accessed directly with a deeplink).

假设导航在此处向下流动:

Assuming the navigation flows downwards here:

Start app:
 - Main Dest 1 (nav to dest 2)
     - Dest 2 (nav to dest 3)
         - Dest 3 (nav to main dest 2)
            --clear--
 - (with clear stack)
   Main Dest 2 (nav to dest 4)
     - Dest 4 (nav to main dest 3)
         --clear-->
 - (with clear stack)
   Main Dest 3
 - Back button should close the app here

由于导航非常动态,因此我无法保证根目录的目的地.例如,即使我可以弹出主要目标2",我也不知道它在堆栈中,因为我可能直接从URL转到了目标4".

Since the navigation is very dynamic, I cannot guarantee the root destination. Even though I could, for example, pop up to "Main Dest 2", I cannot know that it's on the stack since I might have gone directly to "dest 4" from a URL.

我有办法知道哪个目的地是最低的,所以我可以弹出它并清除堆栈?

I there a way of knowing which destination is the lowest so I can pop up to it and clear the stack?

推荐答案

图形的根始终在堆栈上,因此您可以始终 popUpTo 该目标.

The root of your graph is always on the back stack, so you can always popUpTo that destination.

因此,只需确保您的根< navigation> 元素具有与之关联的 android:id :

So just make sure your root <navigation> element has an android:id associated with it:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@+id/main_dest_1">
    <!-- The rest of your graph -->
</navigation>

然后,只要您想弹出整个图形,只需 popUpTo ="@ id/nav_graph" .

Then whenever you want to pop the entire graph, just popUpTo="@id/nav_graph".

当然,根据导航原理,您转到Main Dest 2,Main Dest 3等时,应该弹出整个堆栈.从UX角度来看,用户知道后退按钮何时退出应用程序非常重要-该开始目标正是该路标,供用户知道何时会发生,并防止在用户希望退出您的应用程序前返回第一个屏幕时意外关闭该应用程序.

Of course, as per the Principles of Navigation, you should not be popping the whole stack off when you go to Main Dest 2, Main Dest 3, etc. as it is extremely important from a UX perspective that users know when the back button will exit the app - that start destination is exactly that sign post for users to know when that'll happen and prevents accidental closure of the app when users expect to return to the first screen before exiting your app.

这篇关于导航组件:跳转到动态根目录并清除后退堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆