How to perform custom navigation?

2019-07-29 07:02发布

问题:

I try to using new architecture component called navigation. It's very thrilling and make lesser code than using FragmentManager. Now, I ended up in a case where I have 5 fragments with navigation looks like this:

A -> B -> C -> D -> E

Sometime I have to move user from fragment A directly to E and if back button pressed, I want something like this:

E -> D -> C -> B -> A

But what I got now is:

E -> A

Is there any approachable way to make it happen?

回答1:

OK! if you want to go from E -> A then you need to pop some fragments from fragmentManager. So, you need to do:

var size = fragmentManager!!.backStackEntryCount
var fm: FragmentManager = fragmentManager as FragmentManager
for (i in 0..(size - 1)) {
    fm.popBackStack()
}

in your backPressed event.



回答2:

If you directly Move from E->D now when you want to go back, Check if the Fragment already present in backstack, If present move to that otherwise open again. For this

You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.

Fragment fragmentA = fragmentManager.findFragmentByTag("frag1");
if (fragmentA == null) {
    //not exist
}
else{
   //fragment exist
}

And In your Other scenario where you go A->B->C->D and then want to pop multiple fragments then Yo can do like this in java

 for (int i=0;i<fragmentManager.backStackEntryCount;i++) { // or change the many fragments you want to pop.
     fragmentManager.popBackStack();
 }