Fragment被replace时,会重新走onCreateView()等生命周期,我们写的初始化数据的相关逻辑也会重走,并且重复添加,解决问题的办法有两个
第一种:在fragment中解决
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (null != view) {
ViewGroup parent = (ViewGroup) view.getParent();
if (null != parent) {
parent.removeView(view);
}
} else {
view = inflater.inflate(R.layout.fragment_mian, container, false);
initView(view);// 控件初始化
}
return view;
}
第二种:使用add() hide() show()代替replace()
代替前replace() 伪代码
Fragment aa = new AA();
Fragment bb = new BB();
switch(){
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.content, aa).commit();
break;
case 2:
getSupportFragmentManager().beginTransaction().replace(R.id.content, bb).commit();
break;
}
使用add() hide() show()代替
Fragment aa = new AA();
Fragment bb = new BB();
switch(){
case 1:
switchContent(aa);
break;
case 2:
switchContent(bb);
break;
}
// 标记当前显示Fragment
private Fragment mContent;
/**
* 切换Fragment
* @param to 要显示的Fragment
*/
public void switchContent(Fragment to) {
if (mContent != to) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (!to.isAdded()) { // 未add过
if(mContent != null) {
transaction.hide(mContent).add(R.id.frame_layout, to).commit();
}else{ // 为null,第一次调用,添加第一个Fragment
transaction.add(R.id.frame_layout,to).commit();
}
} else { // 添加过,隐藏当前,显示下一个
transaction.hide(mContent).show(to).commit();
}
mContent = to;
}
}