应用程序处于后台时正确消除对话框碎片的方法

我开始使用 DialogFragment,因为它们在方向更改等方面工作得很好。但我遇到了一个棘手的问题。

我有 AsyncTask,显示进度对话片段,并解散它的 onPostExecute。一切工作正常,除了当 onPostExecute发生时,应用程序是在后台(后按主页按钮,例如)。然后我得到这个错误对话框片段解散-“ Can not perform this action after onSaveInstanceState”。噢。有规律的对话就可以了。但不是片段对话。

所以我想知道,当应用程序在后台时,什么是正确的方法来消除对话片段?我没怎么研究过碎片所以我觉得我漏掉了什么。

25686 次浏览

一个可行的解决方案是在对话框片段中设置 Fragment.setRetainInstance(true),但这不是最好的修复方案。

有时我注意到,我必须将对话框操作排队,让框架首先恢复状态。如果您可以获得当前的 Looper (Activity.getMainLooper())并将其包装在 Handler 中,那么您可以尝试通过在该队列上发布一个 runnable 来将解雇传递到队列的后面。

I often end up using a separate fragment that it retaininstance(true) that has a ResultReceiver. So i pass on that result receiver to my jobs and handle callbacks in its onReceive (often as a router for other receivers). But that might be a bit more work than it is worth if you are using async tasks.

DialogFragment has a method called dismissAllowingStateLoss()

这就是我所做的 (df == dialogFragment):

请确保以这种方式调用对话框:

df.show(getFragmentManager(), "DialogFragment_FLAG");

当您想要关闭对话框时,请进行以下检查:

if (df.isResumed()){
df.dismiss();
}
return;

确保片段(而不是 df)的 onResume ()方法中有以下内容

@Override
public void onResume(){
Fragment f = getFragmentManager().findFragmentByTag("DialogFragment_FLAG");
if (f != null) {
DialogFragment df = (DialogFragment) f;
df.dismiss();
}
super.onResume();
}

这样,如果对话框是可见的,它将被取消。.如果不可见的对话框将被解除下一个片段变得可见(onResume) ..。

我必须这么做才能达到你的目的: 我有一个片段活动,在它上面我显示了一个名为 fragment_RedemptionPayment的对话框片段,它在顶部全局声明。如果在活动进入后台并返回到前台之前显示了 DialogFragment,则下面的代码将其解除。

     @Override
public void onResume() {
super.onResume();
if(fragment_RedemptionPayment.isVisible()){
fragment_RedemptionPayment.dismiss();
}
}

另一种在要求解雇之前检查州政府的新方法是:

if(!dialog.isStateSaved){
dialog.dismiss()
} else {
//Change the UI to suit your functionality
}

通过这种方式,检查状态是否保存,基本上是暂停状态,并调用 onSaveInstanceState

For Java you can use isStateSaved()