Android:当用户在 View 之外按下时如何关闭自定义 View

标签 android view drop-down-menu spinner

我有一个自定义 View ,它由一个按钮和一个在按钮下方动画的 View 组成,该 View 包含多选项目的自定义 View 。当用户按下按钮时,我会显示带有项目的“下拉菜单”。当他们按下下拉菜单之外时,我想隐藏“下拉菜单”。我尝试重写 onTouchEventonInterceptTouchEvent,但这些并不总是被调用。

我查看了 Spinner 的源代码,并注意到 Google 正在使用一个对话框作为我认为的下拉菜单(目前它的定位方式超出了我的范围) 。

有什么方法可以让我的View拦截Window上的所有触摸事件吗?

最佳答案

您可以在顶部 ViewGroup 上实现 onTouchListener(例如,在 LinearLayout 或您正在使用的任何内容上)。

然后,确定自定义 View 的位置:如果触摸位置(使用 event.getX()event.getY() 方法)位于 View 之外(使用myView.getTop()等),然后它可以隐藏它(myView.setVisibility(View.GONE)。

无论如何,它应该返回 false 以允许子 View 处理触摸。

来自 Android 开发指南:

Remember that key events are always delivered to the View currently in focus. They are dispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination.

Note: Android will call event handlers first and then the appropriate default handlers from the class definition second. As such, returning true from these event listeners will stop the propagation of the event to other event listeners and will also block the callback to the default event handler in the View. So be certain that you want to terminate the event when you return true.

关于Android:当用户在 View 之外按下时如何关闭自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737837/

相关文章:

javascript - e.target 和 htmlelement 不能进行比较是有原因的吗?

ios - Swift: 'NSLayoutFormatOptions' 没有名为 'Element' 的成员

ios - 在 UITabBarController 中的 ViewController 中呈现 View

java - 共享首选项不应用更改

android - 在 Google TV 上的 Android Webview 中播放 YouTube 内容时出错

java - 如何在 Eclipse Android 开发中使用自定义 View ?

css - IE8 中的菜单 CSS 问题

c# - 在 C# .net 中通过 Web 表单上的数组填充组合

具有自定义 lint 规则的索引循环中的 Android Studio

android - Android 的 Linux rt- 补丁有人吗?