Skip to content Skip to sidebar Skip to footer

Is There A Way To Check For Popbackstack Call In A Fragment

I have a back stack of a few fragments and I need to know that I have returned to one from another. Similar to when you have onActivityResult I was wondering if you could have a ch

Solution 1:

You Can add Listener for BackStackChange on your Activity page Like,

     getSupportFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                publicvoidonBackStackChanged() {

                       // Your Code Here

                }
            });

Solution 2:

you can do in onViewCreated() method:

if (savedInstanceState == null && !mAlreadyLoaded) {
    mAlreadyLoaded = true;

    // Do this code only first time, not after rotation or reuse fragment from backstack
}
Because when android put fragment on backstack, it only destroy its view, but don't kill instance itself, so mAlreadyLoaded will be still true when fragment will be restored from backstack.

Solution 3:

 getSupportFragmentManager().addOnBackStackChangedListener(
                new FragmentManager.OnBackStackChangedListener() {
                    publicvoidonBackStackChanged() {
                        FragmentManager fm = getSupportFragmentManager();

                        if (fm != null) {
                            int backStackCount = fm.getBackStackEntryCount();
                            if (backStackCount == 0) {


                            }
                        }
                    }
                });

You can use addOnBackStackChangedListener with fm.getBackStackEntryCount(); which will give back stack count of fragments.

Post a Comment for "Is There A Way To Check For Popbackstack Call In A Fragment"