我找了很多解决方案,但好像这不是一个常见的问题。
我想在应用连接到服务器时显示一个不确定的对话框旋转器,然后清除该对话框并在请求完成后显示另一个对话框。我正在使用Fragment
兼容包。问题是,在显示第二个对话框之前,旋转器没有被移除。
以下是显示对话框并应该移除任何当前对话框的代码:
void displayDialog(int type, String message) {
Log.i(logTag, "displayDialog: " + type);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
Log.i(logTag, "removing previous dialog");
ft.remove(prev); //TODO maybe use ((DialogFragment)dialog).dismiss(); ?
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = DialogHelperFragment.newInstance(type, message);
newFragment.show(ft, "dialog");
}
这是我用来排查此 bug 的调用代码:
displayDialog(DialogHelperFragment.DIALOG_PROGRESS, null);
displayDialog(DialogHelperFragment.DIALOG_PURCHASE_SUCCESS, null);
以下是我对应的LogCat输出:
这里是我的对应LogCat输出:
06-25 13:53:35.497: I/tag(11008): displayDialog: 8
06-25 13:53:35.497: I/tag(11008): displayDialog: 7
06-25 13:53:35.897: I/tag Dialog Helper(11008): Creating Dialog: 8
06-25 13:53:35.907: I/tag Dialog Helper(11008): Creating Dialog: 7
问题在于:
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
返回null是因为第一个对话框在调用displayDialog()时尚未创建或附加。
任何提示都将非常有帮助。