Android的对话框中设置取消摸出侧(Android dialog set cancel on t

2019-09-29 12:40发布

我有这样的custom dialogActivty这是内部ActivityGroup

我想点击外表面时,关闭对话框,并试图一切,我在网上找到,使其工作..

我已经试过setCanceledOnTouchOutside(true) -没有工作

我试过了:

public boolean onTouchEvent ( MotionEvent event ) {
  // I only care if the event is an UP action
  if ( event.getAction () == MotionEvent.ACTION_UP ) {
    // create a rect for storing the window rect
    Rect r = new Rect ( 0, 0, 0, 0 );
    // retrieve the windows rect

    this.getWindow ().getDecorView ().getHitRect ( r );
    Log.i(r.toShortString(),r.toShortString());
    // check if the event position is inside the window rect
    boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
    // if the event is not inside then we can close the activity
    if ( !intersects ) {
      // close the activity
      this.dismiss ();
      // notify that we consumed this event
      return true;
    }
  }

并没有太多工作..

正如我在logcat中看到-我认为,从某些原因,对话窗口大小是完全屏蔽就是为什么我没有“外部”接触..

我想可能有做的活动组..任何建议的东西吗?

Answer 1:

好了,所以很多的思考后,我找到了最简单的解决方案:

问题:

从某种原因-虽然我使用的主题是对话,而不是一个全屏幕显示-的getWindow().getDecorView()返回一个搜索覆盖了整个屏幕。

解决方案:

在我的XML文件,我把根元素的ID,我已经改变了上面的函数如下:

private View rootView;

public BaseDialog(Context context, int theme) {
    super(context, theme);  
    //I don't think the next 2 lines are really important - but I've added them for safety  
    setCancelable(true); 
    setCanceledOnTouchOutside(true);    
}

public void setRootView(int resourceId)
{
    this.rootView = findViewById(resourceId);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Rect rect = new Rect();
    rootView.getHitRect(rect);
    if (!rect.contains((int)event.getX(), (int)event.getY()))
    {
        this.dismiss();
        return true;
    }
    return false;       
}       

希望这将帮助别人... :)



文章来源: Android dialog set cancel on touch out side