Недавно сам задавался подобным вопросом.
В итоге был написан такой метод:
public void showFragment(String fragmentName) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Получаем список фрагментов, которые находятся в FragmentManager
ArrayList<Fragment> existingFragments = (ArrayList<Fragment>) fragmentManager.getFragments();
// Фрагмент, который в данный момент отображен на экране
Fragment shownFragment = null;
if(existingFragments != null) {
for(Fragment curFragment : existingFragments) {
if(curFragment.isVisible()) {
shownFragment = curFragment;
break;
}
}
}
// Фрагмент, который необходимо отобразить на экране
Fragment neededFragment = null;
// Если в данный момент на экране не отображен ни один фрагмент, либо отображен, но не тот, который требуется показать
if(shownFragment == null || !shownFragment.getClass().getSimpleName().equals(fragmentName)) {
// Проверяем, есть ли фрагмент, который нужно отобразить, в FragmentManager
if(shownFragment != null)
neededFragment = fragmentManager.findFragmentByTag(fragmentName);
// Если нужного фрагмента нет, то создаем его и добавляем в FragmentManager
if(neededFragment == null) {
switch(fragmentName) {
case "FragmentOne":
neededFragment = new FragmentOne();
fragmentTransaction.add(R.id.fragmentContainer, neededFragment, "FragmentOne");
break;
case "FragmentTwo":
neededFragment = new FragmentTwo();
fragmentTransaction.add(R.id.fragmentContainer, neededFragment, "FragmentTwo");
break;
case "FragmentThree":
neededFragment = new FragmentThree();
fragmentTransaction.add(R.id.fragmentContainer, neededFragment, "FragmentThree");
break;
}
}
// Скрываем старый фрагмент
if(shownFragment != null)
fragmentTransaction.hide(shownFragment);
// Показываем новый фрагмент
fragmentTransaction.show(neededFragment);
fragmentTransaction.commit();
}
}