Android Dialog外部点击事件

本文借鉴:https://www.aliyun.com/jiaocheng/1358172.html。本文只做简单笔记,详情见博主博客!
感谢博主分享!

简介

一、设置是否点击dialog外部取消dialog

  这个直接设置setCanceledOnTouchOutside方法即可。

二、点击外部自己监听事件

  有时候我们不仅仅是需要设置点击外部取消,而是想做一些其他的动作,比如我就遇到过需要把外部点击事件发送给下层Activity的情况。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Make us non-modal, so that others can receive touch events.
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

    // ...but notify us that it happened.
    getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

    // Note that flag changes must happen *before* the content view is set.
    setContentView(R.layout.my_dialog_view);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // If we've received a touch notification that the user has touched
    // outside the app, finish the activity.
    if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
       finish();
       return true;
     }

     // Delegate everything else to Activity.
     return super.onTouchEvent(event);
}

三、设置外部透明

  设置dialog外部透明。

   getWindow().setDimAmount(0F)

你可能感兴趣的:(Android Dialog外部点击事件)