片段和android生命周期

时间:2015-04-01 14:33:24

标签: java android android-fragments

我的Android应用程序有点奇怪。

如果我运行主要活动,然后浏览几个片段,我会在隐藏/取消隐藏应用程序后看到主要活动。如果我按"返回",它将显示隐藏前显示的片段。但有时应用程序会显示我取消隐藏后的最后一个片段。如果可能的话,如何让我的应用程序每次显示最后一个片段?或者我如何让我的应用程序保存其状态?

1 个答案:

答案 0 :(得分:1)

如果我理解,你想要什么时候回来"按下按钮,应显示最后一个片段。为此,您可以依靠addToBackStack方法来处理Back press。 来自Google代码段@ Fragments

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

注意:在这种情况下,newFragment是你的最后一个片段。