以前实现Fragment的切换都是用replace方法实现
public void startFragmentAdd(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_layout, fragment, fragment.getClass().getName())
.commit();
}
replace()方法只是在上一个Fragment不再需要时采用的简便方法。因此,每次切换的时候,Fragment都会重新实例化,重新加载数据。
如果要实现Fragment 切换时不重新实例化,正确的切换方式是add(),切换时hide()当前,add()另一个Fragment;再次切换时,只需hide()当前,show()另一个。
// fragment的切换
private void startFragmentAdd(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
if (current_fragment == null) {
fragmentTransaction.add(R.id.main_layout, fragment).commit();
current_fragment = fragment;
}
if (current_fragment != fragment) {
// 先判断是否被add过
if (!fragment.isAdded()) {
// 隐藏当前的fragment,add下一个到Activity中
fragmentTransaction.hide(current_fragment)
.add(R.id.main_layout, fragment).commit();
} else {
// 隐藏当前的fragment,显示下一个
fragmentTransaction.hide(current_fragment).show(fragment)
.commit();
}
current_fragment = fragment;
}
}