我正在学习如何使用片段。我有三个实例Fragment
在类的顶部被初始化。我将片段添加到这样的活动中:
声明和初始化:
Fragment A = new AFragment();
Fragment B = new BFragment();
Fragment C = new CFragment();
替换/添加:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();
这些摘要运行正常。每个片段都附加到该活动,并毫无问题地保存到后台堆栈。
因此,当我启动A
,,C
然后启动时,B
堆栈如下所示:
| |
|B|
|C|
|A|
___
当我按下“后退”按钮时,它B
被破坏并C
恢复。
但是,当我A
第二次启动fragment 时,它不是从back stack恢复,而是添加到back stack的顶部
| |
|A|
|C|
|A|
___
但是我想恢复A
并销毁所有碎片(如果有的话)。实际上,我只是喜欢默认的反向堆栈行为。
我该如何完成?
预期:(A
应该恢复,并且应该破坏顶部片段)
| |
| |
| |
|A|
___
编辑:(由A–C建议)
这是我尝试的代码:
private void selectItem(int position) {
Fragment problemSearch = null, problemStatistics = null;
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
String backStateName = null;
Fragment fragmentName = null;
boolean fragmentPopped = false;
switch (position) {
case 0:
fragmentName = profile;
break;
case 1:
fragmentName = submissionStatistics;
break;
case 2:
fragmentName = solvedProblemLevel;
break;
case 3:
fragmentName = latestSubmissions;
break;
case 4:
fragmentName = CPExercise;
break;
case 5:
Bundle bundle = new Bundle();
bundle.putInt("problem_no", problemNo);
problemSearch = new ProblemWebView();
problemSearch.setArguments(bundle);
fragmentName = problemSearch;
break;
case 6:
fragmentName = rankList;
break;
case 7:
fragmentName = liveSubmissions;
break;
case 8:
Bundle bundles = new Bundle();
bundles.putInt("problem_no", problemNo);
problemStatistics = new ProblemStatistics();
problemStatistics.setArguments(bundles);
fragmentName = problemStatistics;
default:
break;
}
backStateName = fragmentName.getClass().getName();
fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
ft.replace(R.id.content_frame, fragmentName);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
// I am using drawer layout
mDrawerList.setItemChecked(position, true);
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
问题是,当我启动A
,然后B
,然后按“后退”,B
移除并A
重新开始。并再次按“返回”将退出该应用程序。但是它显示的是一个空白窗口,我必须第三次按下以将其关闭。
另外,当我启动时A
,然后B
,然后C
,然后B
再次...
预期:
| |
| |
|B|
|A|
___
实际:
| |
|B|
|B|
|A|
___
我应该onBackPressed()
使用任何自定义覆盖还是我缺少某些东西?