我的应用程序中有一个带有几个按钮的标签栏,对于这些按钮有一个片段。单击按钮时,我隐藏当前显示的一个,然后显示与单击的按钮相对应的片段。一切都很好,但有时当我从另一个活动返回或在后台有应用程序更长时间时,我会看到所有这些碎片堆积在自己身上。
这种行为的原因是什么,我应该如何解决它?
更新 1:
这就是我恢复实例状态的方式
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentTab = 0;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (fragment1 != null)
ft.show(fragment1);
if (fragment2 != null)
ft.hide(fragment2);
if (fragment3 != null)
ft.hide(fragment3);
if (fragment4 != null)
ft.hide(fragment4);
if (fragment5 != null)
ft.hide(fragment5);
ft.commit();
}
这里是 onTabbarButtonClick 中的切换片段(所有按钮都有相同的监听器)
@Override
public void onClick(View v) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// hide only what is needed and when it is needed
// for example when user clicks currently selected tab then nothing is done
switch (mCurrentTab) {
case 1:
if (v.getId() != R.id.btn1)
ft.hide(fragment1);
break;
case 2:
if (v.getId() != R.id.btn2)
ft.hide(fragment2);
break;
case 3:
if (v.getId() != R.id.btn3)
ft.hide(fragment3);
break;
case 4:
if (v.getId() != R.id.btn4)
ft.hide(fragment4);
break;
case 5:
if (v.getId() != R.id.btn5)
ft.hide(fragment5);
break;
}
// show only what is needed and when it is needed
switch (v.getId()) {
case R.id.btn1:
if (mCurrentTab != 1) {
mCurrentTab = 1;
ft.show(fragment1);
}
break;
case R.id.btn2:
if (mCurrentTab != 2) {
mCurrentTab = 2;
ft.show(fragment2);
}
break;
case R.id.btn3:
if (mCurrentTab != 3) {
mCurrentTab = 3;
ft.show(mFavoritesFragment3);
}
break;
case R.id.btn4:
if (mCurrentTab != 4) {
mCurrentTab = 4;
ft.show(fragment4);
}
break;
case R.id.btn5:
if (mCurrentTab != 5) {
mCurrentTab = 5;
ft.show(fragment5);
}
break;
}
ft.commit();
}