Attach/detach vs replace fragment

Viewed 4963

In the following piece of code, what's the point of using detach/attach fragments instead of just replacing them?

private void showFragment(String tag) {
  String oldTag = mSelectedTag;
  mSelectedTag = tag;
  final FragmentManager fm = getSupportFragmentManager();
  final FragmentTransaction ft = fm.beginTransaction();
  final Fragment oldFragment = fm.findFragmentByTag(oldTag);
  final Fragment fragment = fm.findFragmentByTag(tag);

  if (oldFragment != null && !tag.equals(oldTag)) {
    ft.detach(oldFragment);
  }

  if (fragment == null) {
    ft.replace(R.id.container, getContentFragment(tag), tag);
  } else {
    if (fragment.isDetached()) {
      ft.attach(fragment);
    }
  }
  ft.commit();
}

Why can't I just write something like this?

private void showFragment(String tag) {
  final FragmentManager fm = getSupportFragmentManager();
  final FragmentTransaction ft = fm.beginTransaction();
  ft.replace(R.id.container, getContentFragment(tag), tag);
  ft.addToBackStack(null);
  ft.commit();
}

getContentFragment method, just in case:

 private Fragment getContentFragment(String tag) {
   Fragment fragment = null;
   if (Frag1.TAG.equals(tag)) {
     fragment = new Frag1();
   } else if (Frag2.TAG.equals(tag)) {
     fragment = new Frag2();
   }
   return fragment;
 }
1 Answers
Related