组件导航,使用参数从后退弹出 [英] Component Navigation , pop from backstack with arguments

查看:105
本文介绍了组件导航,使用参数从后退弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个片段,A,B,C;

A-> B<-> C

在B和C之间是循环关系. B或C片段都需要arguments,例如

     val args = Bundle()

     args.putString("StringKeyBC", argValueBtoC)       
     findNavController().navigate(R.id.action_fragmentB_to_fragmentC, args, null)

     args.putString("StringKeyCB", argValueCtoB)       
     findNavController().navigate(R.id.action_fragmentC_to_fragmentB, args, null)

问题在于,每次我在B& amp;之间移动时, C,将片段添加到堆栈中,我不希望这样.如果片段已经要回栈了,我只想弹出它,但是如果我使用popBackStack,就不能再添加参数了:

public boolean popBackStack(@IdRes int destinationId, boolean inclusive)

那么,我如何在两个片段之间进行常量切换而又不必每次都将它们添加回堆栈?

解决方案

您只需在导航操作中添加popUpTo属性,就可以从堆栈中弹出片段.通过这种方式,您可以使用带有参数的操作进行导航,但具有弹出堆栈行为.

例如,您可以将属性app:popUpTo="@+id/fragmentB"添加到动作action_fragmentC_to_fragmentB.这样,每次从fragmentC到fragmentB时,都会从堆栈中弹出fragmentC.

在此处查看带有示例的文档.

还有另一个选项,这可能是您描述的情况的开销,但是允许使用popBackStack方法并发送参数-使用返回结果的导航"方法.为此,片段应使用接收包的方法实现接口(回调).在调用popBackStack之后,使用片段管理器中的addOnBackStackChangedListener触发此方法,提供所有必需的数据. (在如何返回结果?"部分中进行了描述:

The problem is that every time I move between B & C, the fragments are added to back stack and I don't want that. If the fragment is already to back stack I want just to pop it, but if I use popBackStack I can not add arguments anymore:

public boolean popBackStack(@IdRes int destinationId, boolean inclusive)

So, how can I constanlty switch between the two fragments without adding them every time to back stack?

You can pop fragments from back stack simply by adding a popUpTo attribute to a navigation action. This way you navigate using an action with arguments, but with pop back stack behaviour.

For example, you can add attribute app:popUpTo="@+id/fragmentB" to the action action_fragmentC_to_fragmentB. This way you'll be popping fragmentC from backstack each time you go from fragmentC to fragmentB.

See the docs with example for this here.

There's another option, which is likely an overhead for the case you described, but that allows to use popBackStack method and send arguments - using 'navigate back with result' approach. For it fragments should implement an interface (callback) with a method that receives bundle. Use addOnBackStackChangedListener in the fragment manager to trigger this method, providing all the data necessary, after popBackStack is called. (Described here in the section "How to navigate back with a result?": https://medium.com/google-developer-experts/using-navigation-architecture-component-in-a-large-banking-app-ac84936a42c2, and with slightly different implementation here: https://medium.com/@zawadz88/david-vávra-thank-you-for-this-great-article-ae3e602b880a)

这篇关于组件导航,使用参数从后退弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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