如何检查导航目标是否在NavController的后堆栈中? [英] How to check Navigation Destination is in the NavController back stack or not?

本文介绍了如何检查导航目标是否在NavController的后堆栈中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找的是我的片段是否已经在堆栈中.

What I am exactly looking for is that wether my fragment is already in the back stack or not.

例如,我导航到Fragment A到FragmentB.稍后,我导航到Fragment B到FragmentC.现在,我要检入Fragment C,它在后堆栈中有可用的FragmentA.如果是,我想将所有片段弹出到片段A,否则我想添加新的片段A.

For example, I navigate to Fragment A to Fragment B. Later, I navigate to Fragment B to Fragment C. Now, I want to check in the Fragment C that is there Fragment A available in the back stack. If yes, I want to pop out all the fragments up to Fragment A else I want to add new Fragment A.

请确保我要检查片段C中片段A的可用性.

Please make sure I want to check availability of Fragment A in Fragment C.

有运气吗?

谢谢.

推荐答案

我要寻找的是我的片段是否已经存在还是没有后堆栈.

What I am exactly looking for is that wether my fragment is already in the back stack or not.

有一种方法可以使用 NavController .

try {
    val back:NavBackStackEntry = controller.getBackStackEntry(R.id.nav_a)
    Log.d("in_back_stack", back.destination.label.toString())
} catch (ex: IllegalArgumentException){
    Log.d("in_back_stack","no_entry")
}

使用 NavController.getBackStackEntry(...)& destinationId ,您可以轻松地知道片段是否已经在堆栈中.但是请小心使用此方法.如果在后堆栈中未找到 destinationId ,则该方法将引发 IllegalArgumentException .

Using NavController.getBackStackEntry(...) & destinationId you can easily know whether a fragment is already in the back stack or not. But be careful using this method. As the method will throw an IllegalArgumentException if the destinationId is not found in the back stack.

请确保我要检查片段C中片段A的可用性.

Please make sure I want to check availability of Fragment A in Fragment C.

您可以从任何地方进行检查.您只需要参考 NavController .

You can check from anywhere. All you need is reference of the NavController.

这篇关于如何检查导航目标是否在NavController的后堆栈中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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