我的 Android 应用程序出现了一些奇怪的情况。
如果我运行主要 Activity ,然后浏览几个 fragment ,我将在隐藏/取消隐藏应用程序后看到主要 Activity 。如果我按“返回”,它将显示隐藏之前显示的 fragment 。但有时应用程序会向我显示取消隐藏后的最后一个 fragment 。如果可能的话,如何让我的应用程序每次都显示最后一个 fragment ?或者我怎样才能让我的应用程序保存其状态?
最佳答案
如果我理解,您希望在按下“后退”按钮时,应显示最后一个 fragment 。为此,您可以依靠 addToBackStack 方法来处理后退按下。 来自Google代码 fragment @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 是您的最后一个 fragment 。
关于java - Fragment 和 Android 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393603/