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();
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
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With