Android 由父级捕获 onTouch 事件,处理它并传递给子级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12168254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catch onTouch event by parent, handle it and pass to children
提问by Elad92
I tried to understand how Android handle touch event and got a little bit confused. From what I understand touch event are send to the root view and pass down to the children.
I have a FrameLayout
that is a container for Fragment
.
First fragment view is a ScrollView
, second one is some kind of Gallery
(HorizontalListView) and the last one is also FrameLayout
. Only one fragment in the layout each time.
What I want to do is to identify user swipes on the screen, for the app use. I want to count the swipes and do something after some number of swipes.
我试图了解 Android 如何处理触摸事件,但有点困惑。据我所知,触摸事件被发送到根视图并传递给孩子们。我有一个FrameLayout
是Fragment
. 第一个片段视图是一个ScrollView
,第二个是某种Gallery
(HorizontalListView),最后一个也是FrameLayout
。每次布局中只有一个片段。我想要做的是识别用户在屏幕上的滑动,供应用程序使用。我想计算滑动次数并在一定次数的滑动后做一些事情。
I tried to put a OnTouchListener
on the top FrameLayout
but it doesn't get called when the child is the ScrollView
or the Gallery
. I tried to return false
and also true
in the end of onTouch
, but I get same result - it's never being called.
我试图将 aOnTouchListener
放在顶部,FrameLayout
但是当孩子是ScrollView
或时它不会被调用Gallery
。我试图返回false
,也在true
结束时返回onTouch
,但我得到了相同的结果 - 它从未被调用。
How can I do it? I just want to "transparently" handle the touch events and passing them on like I didn't even touch them.
我该怎么做?我只想“透明地”处理触摸事件并将它们传递给我什至没有触摸它们。
回答by JRaymond
My understanding is that it actually goes the other direction. The Child views get their event triggered first (sort of). The root view get's it's dispatchTouchEvent()
called, which propagates the event down to the children's onTouchEvent()
, and then, depending on whether they return true or false, the parent's onTouchEvent()
is called.
我的理解是它实际上走向了另一个方向。子视图首先触发它们的事件(有点)。根视图 getdispatchTouchEvent()
被调用,它将事件向下传播到子视图onTouchEvent()
,然后,根据它们是返回 true 还是 false,onTouchEvent()
调用父视图。
The normal solution for intercepting things like this is to override dispatchTouchEvent(MotionEvent ev)
in one's activity like so:
拦截这样的事情的正常解决方案是像这样覆盖dispatchTouchEvent(MotionEvent ev)
一个人的活动:
@Override
public boolean dispatchTouchEvent (MotionEvent ev) {
// Do your calcluations
return super.dispatchTouchEvent(ev);
}
The documentation for this one is here. Note that you can also override that method in any ViewGroup
(such as a FrameLayout
, etc)
这个文档在这里。请注意,您还可以在任何ViewGroup
(例如 aFrameLayout
等)中覆盖该方法