Android OnTouchEvent and onclick event

时间:2016-10-04 14:43:41

标签: android android-studio android-fragments android-touch-event

I am developing an app, which contains several fragments just like the picture below:

Picture 1

The bottom view is MainActivity, and there are several fragments above MainActivity, which may contain buttons. I want to add a fragment on top in order to listen the OnTouchEvents (gestures), but ignore the onclick events and pass the onclick events to the fragments below.

Here are my questions,

  1. How can I distinguish onTouchEvent and onclick events in my codes?
  2. How can I pass the onclick events to the fragments below?
    I saw some people suggested to use onInterceptTouchEvent(), but I am not sure if this applies to my case and I do not really understand how to use onInterceptTouchEvent().

Update:
I tried to override boolean dispatchTouchEvent(MotionEvent ev) to make the top fragment ignore the click event, however since the first touch event must be MotionEvent.ACTION_DOWN, it seems that there is no way for me to determine whether the touch event is click.

So, is there any other way to do this?

2 个答案:

答案 0 :(得分:0)

来自Documentation

  

只要在ViewGroup的表面上检测到触摸事件(包括在其子表面上),就会调用onInterceptTouchEvent()方法。 如果onInterceptTouchEvent()返回true,则截获MotionEvent,这意味着它不会传递给子节点,而是传递给父的onTouchEvent()方法。

     

onInterceptTouchEvent()方法让父母有机会在子女之前看到任何触摸事件。如果从onInterceptTouchEvent()返回true,则先前处理触摸事件的子视图将收到ACTION_CANCEL,并且从该点开始的事件将发送到父级的onTouchEvent()方法以进行常规处理。 onInterceptTouchEvent()也可以返回false并简单监视事件,因为它们沿着视图层次结构向下移动到它们的常用目标,这些目标将使用它们自己的onTouchEvent()来处理事件。

因此,您必须根据应用程序流逻辑返回true / false(在onInterceptTouchEvent方法中)。如果使用OnTouchListener,则可以避免使用OnClickListener。请参阅文档中的示例以更好地理解它。

答案 1 :(得分:0)

This会让您了解onTouch和onClick是如何不同的。 您可以使用自定义接口将数据传递给较低的片段以进行操作