在努力使我的简单片段程序工作之后,我没有找到以下任何解决方案:我在我的主要活动中管理两个片段:FragmentNeedle和FragmentPlot。一次只能出现一个。用户有两个句子,他可以选择他想要显示的片段。此外,当FragmentPlot显示时,用户应该能够通过按后退键导航回FragmentNeedle。这是我的代码:
public void onButtonPlotPressed()
{
FragmentManager manager = getSupportFragmentManager();
mPlotFragment = (PlotFragment) manager.findFragmentByTag(PlotFragment.class.getSimpleName());
if(mPlotFragment == null)
{
mPlotFragment = new PlotFragment();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.main_layout_center, mPlotFragment, PlotFragment.class.getSimpleName());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
manager.executePendingTransactions();
}
public void OnButtonNeedlePressed()
{
FragmentManager manager = getSupportFragmentManager();
mFragmentNeedle = (FragmentNeedle) manager.findFragmentByTag(FragmentNeedle.class.getSimpleName());
FragmentTransaction ft = manager.beginTransaction();
if(mFragmentNeedle == null)
{
mFragmentNeedle= new FragmentNeedle();
ft.replace(R.id.main_layout_center, mFragmentNeedle, FragmentNeedle.class.getSimpleName());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
manager.executePendingTransactions();
}
}
当显示PlotFragment时,我按回,我将返回NeedleFragment。但现在当我尝试通过按UI按钮更改为Plot Fragment时,它将继续显示PlotFragment。如果我删除了ft.addToBackStack()行,通过按下UI上的按钮,片段之间的切换工作正常,但是我不能用后退键返回。我做错了什么?
答案 0 :(得分:0)
您永远不会将FragmentNeedle
添加到后台。
public void OnButtonNeedlePressed() {
mFragmentNeedle = (FragmentNeedle)manager.findFragmentByTag(FragmentNeedle.class.getSimpleName());
if(mFragmentNeedle == null) {
FragmentManager manager = getSupportFragmentManager();
mFragmentNeedle= new FragmentNeedle();
ft.replace(R.id.main_layout_center, mFragmentNeedle, FragmentNeedle.class.getSimpleName());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
//missing line
ft.addToBackStack(FragmentNeedle.class.getSimpleName());
ft.commit();
manager.executePendingTransactions();
}
}