Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to Fragment Backstack Pop only?

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?

like image 344
Elye Avatar asked Dec 06 '16 00:12

Elye


2 Answers

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();
                }
            });
}
like image 105
Distwo Avatar answered Oct 16 '22 22:10

Distwo


For Kotlin lovers:

supportFragmentManager.addOnBackStackChangedListener {
    if (supportFragmentManager.backStackEntryCount == 0) {
        fab.visibility = VISIBLE
    }
    // Other magic
}
like image 3
Sergio Avatar answered Oct 16 '22 20:10

Sergio