gpt4 book ai didi

Android 对话框设置取消触摸侧

转载 作者:行者123 更新时间:2023-11-29 21:50:23 24 4
gpt4 key购买 nike

我在 Activity 中的 Activty 中有这个自定义对话框

我希望在外部单击时关闭对话框,并尝试了我在网上找到的所有方法以使其正常工作..

我试过 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 中看到的那样 - 我认为出于某种原因对话框窗口大小是全屏的,这就是为什么我无法触摸“外部”..

我认为它可能需要与 Activity 组做一些事情。有什么建议吗?

最佳答案

好吧,经过深思熟虑,我找到了最简单的解决方案:

问题:

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

解决方案:

在我的 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 对话框设置取消触摸侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14549133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com