Is there a way to listen to FragmentTransactions of a FragmentManager?

為{幸葍}努か 提交于 2019-12-04 07:11:52

问题


I have an app with several Fragments which interact to each other. Sometimes I have to add a Fragment, sometimes I replace it.

Is there a way to listen to FragmentTransactions completed, so I can keep track of every time a Fragment is added/shown/replaced?

I've tried fragmentManager.addOnBackStackChangedListener() but unsuccessfully.

I thought of doing something on the onResume() of all of them, but if the app goes to background and foreground I should not do anything to my UI. Only when I interact between them.

Any help/strategy is appreciated.

EDIT: The reason is that I have an overlay that will be shown in the current Fragment. If the user navigates to any other Fragment, I need this overlay to disappear.


回答1:


If I got you correctly you do not need to listen to know this everytime - you just need to know that in regards of your application. If so, write FragmentHelper class (or add some methods to your Base fragment class if you have any) and wrap FragmentManager methods with it, incl. all the additional logic, tracking or everything else you require there.




回答2:


FragmentManager.BackStackEntry and pay attention to getName() by keeping reference to it in an array, and whenever onBackStackChanged() is called you will then know who has been removed or added.

Logic.edit

ArrayList<String> myNames; //will contain the tag id
// when onbackstackchanged is triggered
// get the one on top with getBackstackEntryAt(lastpos).getName()
//use that to check myNames.contains(String)
// i guess you can now put your logic in an if else statement


来源:https://stackoverflow.com/questions/30493716/is-there-a-way-to-listen-to-fragmenttransactions-of-a-fragmentmanager

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