我有随机加载片段的活动。还有一个随机更改片段的按钮。在另一个片段上叠加一个。如何清除以前的片段?
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {initUI();}});
private void initUI() {
ft = getFragmentManager().beginTransaction();
setRandomFragment();
}
private void setRandomFragment() {
Random random = new Random();
int randomFragmentNum = random.nextInt(150);
if (randomFragmentNum < 50) {
randomFragmentNum = 0;
ft.addToBackStack(null);
} else if (randomFragmentNum < 100) {
randomFragmentNum = 1;
ft.addToBackStack(null);
} else if (randomFragmentNum < 150) {
randomFragmentNum = 2;
}
//random choose fragment
switch (randomFragmentNum) {
case 0: {
fragment1 = new LevelOneMyach();
ft.add(R.id.fragCont, fragment1);
ft.commit();
break;
}
case 1: {
fragment2 = new LevelOneTucha();
ft.add(R.id.fragCont, fragment2);
ft.commit();
break;
}
case 2: {
fragment3 = new LevelOneIaschik();
ft.add(R.id.fragCont, fragment3);
ft.commit();
break;
}
}
}
答案 0 :(得分:0)
使用此方法
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();