Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component Navigation , pop from backstack with arguments

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?

like image 852
ghita Avatar asked Aug 17 '19 12:08

ghita


1 Answers

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)

like image 146
Roman Potapov Avatar answered Sep 30 '22 10:09

Roman Potapov