Reputation: 440
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;
}
Upvotes: 3
Views: 5699
Reputation: 54204
Here's the documentation for FragmentTransaction.detach()
(emphasis added):
Detach the given fragment from the UI. This is the same state as when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.
So a detached fragment is still "alive" inside the FragmentManager
; its view has been destroyed but all of its logical state is preserved. So when you call attach()
, you are getting the same fragment back.
FragmentTransaction.replace()
, passing a new
fragment, however, will cause you to wind up using two different instances of the same fragment class, rather than re-using a single instance.
Personally, I've never had a need to use detach()
and attach()
, and have always used replace()
. But that doesn't mean that there isn't a place and time where they're going to be useful.
Upvotes: 5