Android的对话框中设置取消摸出一面 [英] Android dialog set cancel on touch out side

查看:244
本文介绍了Android的对话框中设置取消摸出一面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的自定义对话框内的 Activty 这里面的ActivityGroup

I have this custom dialog inside an Activty which is inside ActivityGroup.

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

I want the dialog to dismiss when clicked outside, and tried everything i found online to make it work..

我试过 setCanceledOnTouchOutside(真) - 没有工作。

I've tried the setCanceledOnTouchOutside(true) - didn't work

我试过:

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中看到 - 我认为这从某种原因,对话框窗口的大小是充满筛选就是为什么我没有外部触摸..

as i see in the LogCat - i think that from some reason the dialog window size is full screened that why i have no "outside" to touch..

我认为它可能有做一些与活动组..任何建议吗?

i think it might have to do something with the activity group.. any suggestions ?

推荐答案

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

Ok so after lots of thinking i found out the most simple solution:

问题:

从一些原因 - 虽然我使用的主题是对话,而不是全屏显示 - 在 getWindow()getDecorView()返回查看覆盖整个屏幕。

From some reason - although the theme I've used is a dialog and not a full screen display - the getWindow().getDecorView() returns a View which covers the whole screen.

解决方案:

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

in my XML file I gave the root element an id and I've changed the function above as follow:

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的对话框中设置取消摸出一面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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