碎片和安卓生命周期



我的安卓应用程序有点奇怪。

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

如果我理解,当按下"后退"按钮时,应该显示最后一个片段。为此,您可以依靠addToBackStack方法来处理Back press。来自谷歌代码片段@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是您的最后一个片段。

最新更新