【问题标题】:Android dialog set cancel on touch out sideAndroid对话框设置取消在触摸侧
【发布时间】:2013-01-27 15:57:24
【问题描述】:

我在Activty 里面有这个custom dialog,它在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 中看到的那样 - 我认为出于某种原因 对话框窗口大小是全屏的,这就是为什么我没有“外部”可以触摸的原因..

我认为这可能与活动组有关.. 有什么建议吗?

【问题讨论】:

    标签: android android-dialog activitygroup


    【解决方案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;       
    }       
    

    希望对某人有所帮助... :)

    【讨论】:

      猜你喜欢
      • 2012-04-07
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多