Search code examples
androidandroid-studioandroid-fragmentsback-stack

Trying avoid add same fragment twice to backStack, popBackStackImmediate always return false


I'm trying avoid adding the same fragment to backStack with this method:

public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, Boolean addToBackStack) {
        String backStateName = fragment.getClass().getName();
        boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);

        if (addToBackStack && !fragmentPopped && fragmentManager.findFragmentByTag(backStateName) == null) {
            fragmentManager
                    .beginTransaction()
//                    .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
                    .replace(R.id.container, fragment)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .addToBackStack(backStateName) // was 'backStateName'
                    .commit();
        } else {
            if (!addToBackStack)
                fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            fragmentManager
                    .beginTransaction()
//                    .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
                    .replace(R.id.container, fragment)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .disallowAddToBackStack()
                    .commit();
        }
    }

Navigation Drawer contains: ImageView with profilePhoto which opens ProfileMainFragment and few categories which opens MainFragmentCategory. Boolean addToBackStack is false when fragment is choosen from navigationDrawerMenu and true when is choosen within fragment (move from MainFragmentCategory to DetialFragmentCategory) or click profilePhoto in navigationDrawer.

fragmentPopped is always false, why is that so? Even if I click profilePhoto and again profilePhoto in navigationDrawer. It should avoid to add it to backStack for a second (and third, and fourth...) time, but it didn't.

Any idea how can I make it right?


Solution

  • You can add the following code before you replace your fragment.

    // Replace fragmentCotainer with your container id
    Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentCotainer);
    // Return if the class are the same
    if(currentFragment.getClass().equals(fragment.getClass())) return;