سؤال

I have an Activity that handles my fragments. I created the following method to add/replace fragments and add them (or not) to the backstack:

public void startFragment(CCFragment fragment, boolean addToBackStack) {
    final String fragmentTag = fragment.getClass().getSimpleName();
    final FragmentManager fragmentManager = getSupportFragmentManager();

            // If my fragment is already in the backstack, I don't want to add 
            // it again, but go back to it:
    boolean fragmentPopped=false;
    if(fragmentManager.findFragmentByTag(fragmentTag)!=null){
        fragmentPopped=true;
        fragmentManager.popBackStack(fragmentTag,0);
    }

            //If it is not, I want to add/replace it
    if (!fragmentPopped) {
        fragment.setFragmentDelegate(this);
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.replace(CONTENT_VIEW_ID, fragment, fragmentTag);
        if (addToBackStack)
            fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

This works fine, until the following scenario happens:

startFragment(F1, false); //nothing in the backstack

startFragment(F2, true); //F1 in the backstack

startFragment(F3, false); //F1 in the backstack

startFragment(F1, false); -> when I call this, it enters the "if" and popBackStack won't work, so my app stays at the F3 instead of going back to F1. If I press the back button, then the app goes to F1...

So what am I doing wrong here? I already checked if the names are being stored right.

هل كانت مفيدة؟

المحلول

ft.addToBackStack(tag);

I'm not certain on this, but when you add a frag to the back stack, I believe you have to tag it (again). In your code, you're not supplying a tag, but using null, so there's no tag to search for, and even if it would otherwise use the original tag, you're overwriting it with null.

Edit: Use the following to verify the name of your tags on the backstack match the tags you originally assigned. I still believe your null is overwriting them.

FragmentManager mgr = getFragmentManager();                 
BackStackEntry be = mgr.getBackStackEntryAt(mgr.getBackStackEntryCount()-1);
String tag be.getName();

System.out.println("tag " + tag);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top