Android:当用户在视图之外按下时如何关闭自定义视图
我有一个自定义 View
,它由一个按钮和一个在按钮下方动画的视图组成,其中包含多选项目的自定义视图。当用户按下按钮时,我会显示带有项目的“下拉菜单”。当他们按下下拉菜单之外时,我想隐藏“下拉菜单”。我尝试覆盖 onTouchEvent
和 onInterceptTouchEvent
,但这些并不总是被调用。
我查看了 Spinner
的源代码,并注意到 Google 正在使用一个对话框作为我认为的下拉菜单(目前它的定位方式超出了我的范围)。
有什么办法可以让我的 View
拦截 Window
上的所有触摸事件吗?
I have a custom View
, which consists of a button, and a view that animates in below the button that contains a custom view of multi-choice items. When the user presses the button, I show the "dropdown" with the items. I want to hide the "dropdown" when they press outside of the dropdown. I tried overriding the onTouchEvent
and the onInterceptTouchEvent
, but these aren't always called.
I took a look at the source for the Spinner
, and noticed that Google is using an Dialog for what I believe to be its dropdown (how it is being positioned is beyond me at this point).
Is there any way I can have my View
intercept ALL touch events on the Window
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在顶部
ViewGroup
(例如,在LinearLayout
或您正在使用的任何内容上)实现onTouchListener
。然后,确定自定义视图的位置: 如果触摸位置(使用
event.getX()
和event.getY()
方法)位于视图之外(使用 < code>myView.getTop() 等),然后它可以隐藏它(myView.setVisibility(View.GONE
))。无论如何,它应该
返回 false< /code> 允许孩子们
View
来处理触摸来自android开发指南:
You can implement the
onTouchListener
on the topViewGroup
(e.g., on aLinearLayout
or whatever you're using).Then, determine the position of your custom view: If the touch position (using
event.getX()
andevent.getY()
methods) is outside the View (usingmyView.getTop()
, etc.), then it can hide it (myView.setVisibility(View.GONE
).In any case, it should
return false
to allow the childrenView
s to handle the touch.From the android dev guide:
我不知道它是如何工作的,但是
TouchDelegate
乍一看,可能是一个解决方案。另外,Activity.onTouchEvent( )
可能值得一试。如果它们不适用(即您不知道如何使用
TouchDelegate
并且您的布局具有可以在“下拉”视图之外执行触摸的按钮),您可以考虑 拦截事件,同时它仍然“向上”朝向视图。I have no idea about how it works, but a
TouchDelegate
could be a solution at first glance. Also,Activity.onTouchEvent()
might be worth a check.If they're not applicable (i.e. you don't know either how to use
TouchDelegate
and your layout has buttons that could get the touches performed outside the "dropdown" view), you could consider intercepting the event while it's still going "up" towards views.