在下面的代码中,使用detach
/attach
fragment 而不是仅仅替换
它们有什么意义?
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();
}
为什么我不能写这样的东西?
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
方法,以防万一:
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;
}
最佳答案
这是 FragmentTransaction.detach()
的文档(强调已添加):
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.
因此 分离的 fragment 在 FragmentManager
中仍然“活跃”;它的 View 已被破坏,但其所有逻辑状态都得到保留。因此,当您调用 attach()
时,您将得到相同的 fragment 。
FragmentTransaction.replace()
,传递一个新
fragment ,然而,将导致您最终使用同一 fragment 类的两个不同实例,而不是重新使用单个实例。
就个人而言,我从来不需要使用 detach()
和 attach()
,并且一直使用 replace()
.但这并不意味着它们在任何地方和时间都不会派上用场。
关于android - 附加/分离与替换 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46246180/