How to perform custom navigation?

我们两清 提交于 2019-12-24 12:13:15

问题


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


来源:https://stackoverflow.com/questions/56270337/how-to-perform-custom-navigation

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