Is there a way to listen to FragmentTransactions o

2019-03-07 05:14发布

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.

2条回答
再贱就再见
2楼-- · 2019-03-07 05:46

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.

查看更多
贼婆χ
3楼-- · 2019-03-07 05:54

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
查看更多
登录 后发表回答