How to listen to Fragment Backstack Pop only?
Asked Answered
C

2

7

I wanted to know when a Fragment has been pop from backstack.

I have my code as below

private void setupChildFragmentPopListener() {
    getChildFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                @Override
                public void onBackStackChanged() {
                    // Do whatever I want
                }
            });
}

However, this code got triggered both when add and pop fragment. How could I have a way to listen only to pop fragment? Or a way to filter out in the onBackStackChanged() function if it is not pop?

Coerce answered 6/12, 2016 at 0:6 Comment(0)
S
5

You can keep a count of the backstack entries and compare it everytime your onBackStackChanged() is called.

private void setupChildFragmentPopListener() {
    getChildFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                @Override
                public void onBackStackChanged() {
                    int backCount = getChildFragmentManager().getBackStackEntryCount();
                }
            });
}
Scincoid answered 6/12, 2016 at 0:23 Comment(1)
Thanks that helps!Coerce
T
4

For Kotlin lovers:

supportFragmentManager.addOnBackStackChangedListener {
    if (supportFragmentManager.backStackEntryCount == 0) {
        fab.visibility = VISIBLE
    }
    // Other magic
}
Tergum answered 2/5, 2020 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.