如何在将进度对话框作为片段进行管理时设置其不可取消?

18

我正在使用作为FragmentProgressDialog。即使我将ProgressDialog设置为不可取消,后退按钮仍将从堆栈中删除该Fragment。我的内部类看起来像这样:

public static class ProgressDialogFragment extends DialogFragment {

    private DialogStyle dialogStyle;

    public static ProgressDialogFragment newInstance(String title, String message) {
        ProgressDialogFragment fragment = new ProgressDialogFragment();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putString("message", message);
        fragment.setArguments(args);

        return fragment;
    }

    public void setDialogStyle(DialogStyle dialogStyle) {
        this.dialogStyle = dialogStyle;
    }


    @Override
    public ProgressDialog onCreateDialog(Bundle savedInstanceState) {
        String title = getArguments().getString("title");
        String message = getArguments().getString("message");

        ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);

        if(dialogStyle!=null) {
            switch (dialogStyle) {
                case CANCELABLE:
                    progressDialog.setCancelable(true);
                    break;
                case NON_CANCELABLE:
                    progressDialog.setCancelable(false);
                    break;

            }
        } else {
            progressDialog.setCancelable(false);
        }

        progressDialog.show();

        return progressDialog;
    }
}

然后我公开的方法是:

public void showProgressDialog(String title, String message, DialogStyle dialogStyle) {
            Fragment prev = fragmentManager.findFragmentByTag("progress dialog");
            if(prev!=null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);

            DialogFragment newFragment = ProgressDialogFragment.newInstance(title, message);
            ((ProgressDialogFragment)newFragment).setDialogStyle(dialogStyle);
            newFragment.show(fragmentManager, "progress dialog");
        }

这里明显的困惑在于,后退按钮会移除ProgressDialog,因为它被视为一个Fragment来管理。那么,我该如何使Dialog不可取消呢?

尝试下面这个方法似乎有点奇怪:

@Override
    public void onBackPressed() {
        if(fragmentManager.fragmentManager.findFragmentByTag("progress dialog")!=null) {

        }
    }

Android似乎在说ProgressDialog不应再使用,而是应该“在布局中使用ProgressBar”。http://developer.android.com/guide/topics/ui/dialogs.html。他们没有说明原因,但我想这可能是为了避免在等待后处理异常事件(如失败的服务器调用、应用程序从后台任务返回等)时出现混乱。 - Lucy
2个回答

39

你为什么不尝试在DialogFragment上调用setCancelable(false),而不是使用ProgressDialog呢?


1
很好的点子!就像这个简单的public void setDialogStyle(DialogStyle dialogStyle) { this.setCancelable(dialogStyle==DialogStyle.CANCELABLE); } (我在这里使用枚举) - LuxuryMode
setCancelable 也适用于 ProgressDialog。不理解您所说的“而不是”的含义。 - Mubashar Abbas

11

您还可以在ProgressDialog上使用setCancelable(false)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接