如何通过在 Android 中单击对话框来关闭该对话框?
我看过几篇关于如何通过单击外部来关闭对话框的帖子。但是有没有办法通过单击对话框窗口内部来获得相同的功能?
对话框是否有任何侦听器可以检测对话框窗口上的点击?
I have seen several posts on how to dismiss a dialog by clicking on the outside. But is there a way to get the same functionality by clicking the inside the dialog window?
Are there any listeners for the Dialog that would detect a tap on the Dialog Window?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
重写
Dialog.onTouchEvent(. ..)
捕获屏幕上任意位置的任何点击。要通过点击任意位置关闭对话框:此代码片段无需调用
dialogObject.setCanceledOnTouchOutside(true);
。Overriding
Dialog.onTouchEvent(...)
catches any tap, anywhere on the screen. To dismiss the dialog by tapping anywhere:This snippet nullifies the need to call
dialogObject.setCanceledOnTouchOutside(true);
.大概您想要检测对话框范围内任何位置的触摸事件。如果您正在创建自定义对话框(即通过将一组
View
组装到某种布局View
中,然后设置父View
使用.setContentView()
作为对话框的主要内容视图),那么也许您可以简单地为该内容父级View
设置一个onTouch
监听器。此外,您可以使用mDialog.findViewById()
获取视图,因此,如果您使用AlertDialog
,也许您可以以某种方式确定要使用的资源 ID抓住它的主布局View
。Presumably you want to detect a touch event anywhere within the bounds of a dialog. If you're creating a custom dialog (i.e. by assembling a set of
View
s into a layoutView
of some sort, and then setting the parentView
as the dialog's main content view using.setContentView()
) then perhaps you could simply set anonTouch
listener to that content parentView
. Furthermore, you could grab hold of views usingmDialog.findViewById()
, so if for example you were using anAlertDialog
, perhaps you could determine somehow what resource ID to use to grab hold of its main layoutView
.如果您的对话框中有一个布局,您可以将其作为视图引用,并在其上放置一个 onClickListener 。因此,假设您的对话框具有自定义布局,并且可以查看整个对话框,请获取对此的引用。
例如,假设一个对话框有一个名为 mainll 的 LinearLayout,其中包含您的自定义视图,您将:
然后,只要在 LinearLayout 中单击任何内容,它就会注册一个单击事件。
If you have a Layout in your Dialog, you could get a reference to that as view, and put a onClickListener on that. So assuming your dialog has a custom layout, and view for the entire dialog, get a reference to that.
For instance, assuming a dialog has a LinearLayout named mainll, that contains your custom views, you would:
Then anytime anything is clicked within the LinearLayout, it will register a click event.
您始终可以创建自己的对话框活动,并在用户单击要关闭对话框的区域时调用 finish()。
You can always create your own Dialog activity and call finish() when the user clicks the area that you want to close your Dialog.
这是一个示例,解释了如何在对话框中处理 onTouch 事件。诀窍在于创建自定义侦听器。
http://about-android.blogspot.co.uk /2010/02/create-custom-dialog.html
Here is an example which explains how to handle onTouch events within the dialog. The trick is in creating a custom listener.
http://about-android.blogspot.co.uk/2010/02/create-custom-dialog.html