安卓Dialog屏蔽空白区域和物理返回按键的作用

在开发过程中,弹出的Dialog表示正在进行某项后台操作,提示用户等待,而且有些情况下不希望用户手动操作去关闭Dialog,打断这个操作。

此时有两种情况
1.用户点击对话框视图其余的空白处
2.用户点击了手机的物理返回按钮

AlertDialog.Builder builder = new AlertDialog.Builder(context);//实例化一个对话框
  • 屏蔽点击空白区域
builder.setCanceledOnTouchOutside(false);//调用这个方法时,按对话框以外的地方不起作用。按返回键还起作用;
  • 屏蔽物理返回按键:
builder.setCancelable(false);、// 调用这个方法时,按对话框以外的地方不起作用。按返回键也不起作用

源码分析

1.下面是Dialog中的返回按键的监听方法,mCancelable 表示的是否可以手动关闭,默认是true , 可以点击返回按钮关闭 ,通过setCancelable(boolean bool) 设置。

/**
     * Called when the dialog has detected the user's press of the back
     * key.  The default implementation simply cancels the dialog (only if
     * it is cancelable), but you can override this to do whatever you want.
     */
    public void onBackPressed() {
        if (mCancelable) {
            cancel();
        }
    }
  1. 下面是 setCanceledOnTouchOutside(boolean bool) ,如果设置的是true,表示可以点击其他区域关闭,这个时候点击返回按钮也同时可以关闭
/**
     * Sets whether this dialog is canceled when touched outside the window's
     * bounds. If setting to true, the dialog is set to be cancelable if not
     * already set.
     * 
     * @param cancel Whether the dialog should be canceled when touched outside
     *            the window.
     */
    public void setCanceledOnTouchOutside(boolean cancel) {
        //这个与操作注意
        if (cancel && !mCancelable) {
            mCancelable = true;
        }

        mWindow.setCloseOnTouchOutside(cancel);
    }

猜你喜欢

转载自blog.csdn.net/ysq_chris/article/details/80982675
今日推荐