I have a very simple code where I use Action Bar with tab fragments. It works fine after load, but after orientation change it goes crazy. The old fragment also visible (why
I found a very simple solution to avoid fragments duplication:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Fragment currentFragment = getFragmentManager().findFragmentByTag(CURRENT_FRAGMENT_TAG);
if (currentFragment == null || !currentFragment.getClass().equals(mFragment.getClass())) {
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.add(android.R.id.content, mFragment, CURRENT_FRAGMENT_TAG);
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.remove(mFragment);
}
The key of the solution is in the condition:
currentFragment == null || !currentFragment.getClass().equals(mFragment.getClass())
This condition is valid ONLY if the classes of the fragments are different. In case you have different instances of the same class you have to put an extra attribute in your fragments to recognize his function (or the association with and to make the condition !currentFragment.getClass().equals(mFragment.getClass()) true: for example you can use the FragmentTransaction tag feature.
Bye, Alex.