Get fragment from backstack for second time

2019-09-12 00:02发布

问题:

i'm currently working on browser app for an android. I'm managing new tabs with fragments. So everything is working fine when user open new tab B, and then go back again to tab A. The problem appear when from A he try to go back again to B. With other words its not working when you tries to pop back same fragment for the second time.

This is how I'm adding new tabs- fragments

    android.app.Fragment f1 = new FragmentHolder();
    allFragments.add(f1);
    getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, f1).addToBackStack(fragmentTags[allFragments.size()-1]).commit();

and here how I'm popping back the fragment

boolean chkFlag = getFragmentManager().popBackStackImmediate(currentTag.getFragmentTAG(),0);

I appreciate your help in advance.

回答1:

Use below function in your Activity,

private void loadFragmentAnimated(Fragment fragment, Bundle args, int containerId, String title)
    {
        fragment.setArguments(args);
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(containerId, fragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

Then Added Fragment by using ,

loadFragmentAnimated(c, null, R.id.container_name, "title");

And remove fragment by using,

getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.container_name)).commit();