Skip to content Skip to sidebar Skip to footer

How To Perform Custom Navigation?

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

Solution 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 in0..(size - 1)) {
    fm.popBackStack()
}

in your backPressed event.

Solution 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.

FragmentfragmentA= 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();
 }

Post a Comment for "How To Perform Custom Navigation?"