我正在使用 Android 支持库 (v4) 和 ActionBarSherlock。我正在尝试以编程方式关闭进度对话框。我编写了一个小型实用程序类来帮助进行对话管理。
该对话框从AsyncTask.onPreExecute
. 它会正确显示。然后我通过旋转设备来触发配置更改,这会破坏活动(onDestroy 调用AsyncTask.cancel(true)
)。AsyncTask.onCancelled
被调用,并且在我试图关闭对话框的这个方法中。但什么也没有发生。以下是显示和关闭对话框的辅助函数:
public abstract class DialogHelperActivity extends SherlockFragmentActivity {
protected void showProgressDialog(final String msg, final String tag){
FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
DialogFragment dialogFragment = ProgressDialogFragment.newInstance(msg);
ft.add(dialogFragment, tag);
ft.disallowAddToBackStack();
ft.commitAllowingStateLoss(); //If I try with regular commit(), exceptions are thrown.
}
protected void closeDialog(final String tag){
FragmentManager fm = this.getSupportFragmentManager();
Fragment dialogFragment = fm.findFragmentByTag(tag);
if(dialogFragment != null){
FragmentTransaction ft = fm.beginTransaction();
ft.remove(dialogFragment);
ft.commitAllowingStateLoss();
} else {
System.err.println("dialog not found!"); //This line is hit always
}
}
public static class ProgressDialogFragment extends SherlockDialogFragment {
static ProgressDialogFragment newInstance(final String msg) {
ProgressDialogFragment adf = new ProgressDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("alert-message", msg);
adf.setArguments(bundle);
return adf;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setCancelable(false);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style,theme);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
String message = bundle.getString("alert-message");
ProgressDialog dialog = new ProgressDialog(getActivity());
if(message != null){
dialog.setMessage(message);
}
dialog.setCancelable(false);
dialog.setIndeterminate(true);
return dialog;
}
}
}
旋转设备后,AsyncTask 被取消。我closeDielog
从onPostExecute
也从打来电话onCancelled
。对话框永远不会关闭,因为找不到标签 ID(findFragmentByTag
返回 null)。我对此感到困惑。showProgressDialog
该标签是我的实现活动中的静态字符串,因此在调用和之间不会丢失或更改它closeDialog
。
任何想法/提示/建议将不胜感激。
谢谢。