Alex
Alex

Reputation: 1644

Android Fragments - remove fragment from back stack if already exists

I have some fragments which will be replaced by following method. I think there's something wrong with my code because I want to prevent from adding multiple times a fragment into the back stack. If I click on fragment B twice, all instances will be added to the back stack and pressing back button will be passed through the two created instances.

public void replaceFragment(Fragment fragment, boolean addToBackStack, boolean customAnimation) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    String tag = fragment.getClass().getSimpleName();
    if (customAnimation) {
        transaction.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_bottom, R.anim.slide_in_bottom, R.anim.slide_out_bottom);
    }
    transaction.replace(R.id.fragment_container, fragment, tag);

    // remove from back stack if exists
    // always return false!
    boolean f = manager.popBackStackImmediate(tag, 0);

    if (addToBackStack) {
        transaction.addToBackStack(tag);
    }
    transaction.commit();
}

Upvotes: 4

Views: 5676

Answers (2)

Ghazal
Ghazal

Reputation: 383

try this on your activity onBackPressed method :

  @Override
    public void onBackPressed() {
        FragmentManager fm = getSupportFragmentManager();

        if (fm.getBackStackEntryCount() > 0) {
            if (fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("your fragment tag")) {
                fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }

Upvotes: 0

Daniel Nugent
Daniel Nugent

Reputation: 43322

Keep it simple and just add to the back stack if needed. If the Fragment being added is the same class as the current Fragment, don't add to the back stack:

public void replaceFragment(Fragment frag) {
    FragmentManager manager = getSupportFragmentManager();
    if (manager != null){
        FragmentTransaction t = manager.beginTransaction();
        Fragment currentFrag = manager.findFragmentById(R.id.content_frame);

        //Check if the new Fragment is the same
        //If it is, don't add to the back stack
        if (currentFrag != null && currentFrag.getClass().equals(frag.getClass())) {
            t.replace(R.id.content_frame, frag).commit();
        } else {
            t.replace(R.id.content_frame, frag).addToBackStack(null).commit();
        }
    }
}

Upvotes: 6

Related Questions