Component Navigation , pop from backstack with arguments

落爺英雄遲暮 提交于 2019-12-11 04:25:06

问题


Let's say I have three fragments, A, B, C;

A -> B <-> C

Between B and C it is a circular relationship. Either B or C fragments requires arguments, example

     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)

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?


回答1:


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.

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)



来源:https://stackoverflow.com/questions/57536179/component-navigation-pop-from-backstack-with-arguments

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