I was struggling with adding a gesture detector to a subview in my project. Do I override the parent's onTouchEvent
or the child's onTouchEvent
? Do I make an OnTouchListener
and add the gesture detector there? The documentation shows an example for how to add a gesture detector to the activity itself but it is not clear how to add it to a view. The same process could be used if subclassing a view (example here), but I want to add the gesture without subclassing anything.
This is the closest other question I could find but it is specific to a fling gesture on an ImageView
, not to the general case of any View
. Also there is some disagreement in those answers about when to return true
or false
.
To help myself understand how it works, I made a stand alone project. My answer is below.
This example shows how to add a gesture detector to a view. The layout is just a single
View
inside of an Activity. You can use the same method to add a gesture detector to any type of view.We will add the gesture detector to the green
View
.MainActivity.java
The basic idea is to add an
OnTouchListener
to the view. Normally we would get all the raw touch data here (likeACTION_DOWN
,ACTION_MOVE
,ACTION_UP
, etc.), but instead of handling it ourselves, we will forward it on to a gesture detector to do the interpretation of the touch data.We are using a
SimpleOnGestureListener
. The nice thing about this gesture detector is that we only need to override the gestures that we need. In the example here I included a lot of them. You can remove the ones you don't need. (You should always returntrue
inonDown()
, though. Returning true means that we are handling the event. Returning false will make the system stop giving us any more touch events.)It is a quick setup to run this project, so I recommend you try it out. Notice how and when the log events occur.