Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after add a fragment the previous fragment still visible

At first, I use the method replace to add fragments to back stack, then I found when I press back key,the fragment in stack will invoke the onCreateView again, I also found this behavious in api demos, so I think it is not a bug, but I would like achieve the effect like activity's behave that when I press the back key the previous activity would not invoke the onCreate method.

Later I found fragmentManager.add() could achieve my idea, but another probrolem appear, when add the second fragment, the previous fragment still visiable.

Could anyone help me?

FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction2 = manager.beginTransaction();
        transaction2.add(R.id.fl, f2);
        transaction2.addToBackStack("Fragment2");
        transaction2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction2.commit();
like image 814
Camus Avatar asked Nov 13 '22 04:11

Camus


1 Answers

Got back to using replace and just add a check to see if the bundle is null.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    ...
    if (savedInstanceState == null) {
        // do work 
        // If the view is being recreated this code won't run
    }
    ...
}
like image 78
Larry McKenzie Avatar answered Nov 15 '22 13:11

Larry McKenzie