DialogFragment的与BackStack的组合让我感到困惑,希望有人能帮助我。
根据我所了解的,有两种常见的显示DialogFragment的方法。一种是通过show()方法,另一种是通过普通添加事务来添加片段(从检查中,这实际上是show()在内部执行的操作)。
我的问题在于理解addToBackstack()方法在整个过程中的作用,特别是在调用show()方法之前将事务添加到backstack中时,例如在此示例中:
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
在上面的示例中,在显示新的DialogFragment之前,我们检查是否有其他可显示的DialogFragment,将其删除并将此过程添加到后退栈中(我假设这是为了在删除新的DialogFragment时显示先前的DialogFragment)。然后,我们通过show()方法显示新的DialogFragment。但我没有看到这种方法与仅调用show()方法之间的任何区别。我在测试项目中检查了一下,按顺序显示多个DialogFragments时,DialogFragment的内部实现会自动处理一切,这意味着当我触摸返回按钮时,先前的DialogFragment仍然会被显示。
那么,为什么在DialogFragments的上下文中使用addToBackStack呢?