防止后退按钮取消 DialogFragment [英] Preventing the back button from cancelling a DialogFragment

查看:44
本文介绍了防止后退按钮取消 DialogFragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以创建和弹出 DialogFragment 的 Fragment,但是当我点击后退按钮时,即使我明确调用了 setCancelable(false),它也会关闭对话框;有什么办法可以让我的 DialogFragment 对后退按钮不敏感?

I have a Fragment that can create and pop up a DialogFragment, but when I hit the back button, it dismisses the dialog even though I explicitly call setCancelable(false); Is there any way for my DialogFragment to be insensative to the back button?

public class LoadingDialogFragment extends DialogFragment
{
    String title;
    String msg;

    public LoadingDialogFragment()
    {
        this.title = "Loading...";
        this.msg = "Please wait...";
    }
    public LoadingDialogFragment(String title, String msg)
    {
        this.title = title;
        this.msg = msg;
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState)
    {
        final ProgressDialog dialog = new ProgressDialog(getActivity());

        dialog.setTitle(title);
        dialog.setMessage(msg);
        dialog.setIndeterminate(true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        return dialog;
    }

}

我从 AsyncTask 创建了 DialogFragment:

I create the DialogFragment from an AsyncTask:

private class GpsTask extends AsyncTask<String, Integer, Integer>
{
    //ProgressDialog dialog;
    @Override
    protected void onPreExecute()
    {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        DialogFragment newFragment = new LoadingDialogFragment("Gathering Location", "Acquiring GPS lock...");
        ft.addToBackStack(null);
        newFragment.show(ft, "dialog");
    }

    @Override
    protected Integer doInBackground(String... params)
    {
        //acquire a GPS lock and grab a few position updates
    }

    @Override
    protected void onProgressUpdate(Integer... input) { }

    @Override
    protected void onPostExecute(Integer result)
    {
        getSupportFragmentManager().popBackStackImmediate();
    }
}

推荐答案

如何使用 setCancelable?你试了吗?

How about using setCancelable? Did you try it?

来自文档:

控制显示的对话框是否可取消.用这个代替直接调用Dialog.setCancelable(boolean),因为DialogFragment需要基于此改变其行为

Control whether the shown Dialog is cancelable. Use this instead of directly calling Dialog.setCancelable(boolean), because DialogFragment needs to change its behavior based on this

对于自定义 DialogFragment

onCreateDialog

这篇关于防止后退按钮取消 DialogFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆