Best Way To Switch Between Two Fragments
Solution 1:
I ended up adding both of the fragments using the support fragment manager and then using detach/attach to switch between them. I was able to use commitAllowingStateLoss() because I retain the state of the view elsewhere, and manually set the correct fragment in onResume().
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransactionfragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.my_layout, newAFragment(), TAG_A);
fragmentTransaction.add(R.id.my_layout, newBFragment(), TAG_B);
fragmentTransaction.commit();
}
publicvoidonResume() {
super.onResume();
if (this.shouldShowA) {
switchToA();
} else {
switchToB();
}
}
privatevoidswitchToA() {
AFragmentfragA= (AFragment) getSupportFragmentManager().findFragmentByTag(TAG_A);
FragmentTransactionfragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.detach(getSupportFragmentManager().findFragmentByTag(TAG_B));
fragmentTransaction.attach(fragA);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
}
Solution 2:
You might want to consider using a ViewPager
in your parent Activity so you can switch between the Fragments.
So you would be able to swipe through them.
if you want to persist their state during a session even if the parent activity is destroyed, you need to make them Parcelable
, so you can save the state even if the class isn't instantiated at that time. You also need to do this if your rotating your device and want to keep the current situation/data on the Screen.
You should write them to a Parcelable
in their onPause
methods and recreate them from it in the onResume
one. This way it doesn't matter if they are destroyed or have to be recreated due to changes in the devices orientation.
if you want to be able to switch between those fragments with the Backbutton, you can catch the buttonClick for onBackPressed
and handle it accordingly.
If you need to figure out what Fragment your displaying at a given time you ask your ViewPager
what Fragment he is displaying at that time, so you don't have to keep track, you can just ask someone who knows, if you need to know it.
Post a Comment for "Best Way To Switch Between Two Fragments"