由父级捕获onTouch事件,处理它并传递给子级 [英] Catch onTouch event by parent, handle it and pass to children

查看:414
本文介绍了由父级捕获onTouch事件,处理它并传递给子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Android如何处理触摸事件,并有点困惑。从我所理解的触摸事件发送到根视图并传递给孩子们。
我有一个 FrameLayout Fragment 的容器。
第一个片段视图是 ScrollView ,第二个是 Gallery (Horizo​​ntalListView)一个也是 FrameLayout 。每次只有一个片段在布局。
我想做的是在屏幕上识别用户滑动,以供应用程序使用。

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.

我试图把一个 OnTouchListener 放在顶部 FrameLayout ,但是当孩子是 ScrollView 图库。我试图在结束时返回 false 以及 true c>,但我得到相同的结果 - 它从来没有被调用。

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.

我该怎么办?
我只是想透明地处理触摸事件,并传递他们,就像我甚至没有触摸他们。

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.

提前感谢,
Elad

Thanks in advance, Elad

推荐答案

我的理解是,它实际上走另一个方向。 Child视图首先触发它们的事件(排序)。根视图get是 dispatchTouchEvent()调用,它将事件传播到子 onTouchEvent(),然后,取决于它们返回true还是false,调用父类的 onTouchEvent()

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.

原谅我测试这个,但我认为正常的解决方案,拦截这样的事情是重写 dispatchTouchEvent(MotionEvent ev)在一个人的活动如下:

Forgive me for not testing this, but I think the normal solution for intercepting things like this is to override dispatchTouchEvent(MotionEvent ev) in one's activity like so:

@Override
public boolean dispatchTouchEvent (MotionEvent ev) {
  // Do your calcluations
  return super.dispatchTouchEvent(ev);
}

这个文档是此处。请注意,您还可以在任何 ViewGroup (例如 FrameLayout 等)中覆盖该方法

The documentation for this one is here. Note that you can also override that method in any ViewGroup (such as a FrameLayout, etc)

这篇关于由父级捕获onTouch事件,处理它并传递给子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆