Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Implementing the onTouchEvent for the MapActivity

2 min read

Android View classes expose an onTouchEvent(MotionEvent ev) method. As the name already suggests, by overriding this method you can handle touch events done by the user on the current view.
@Override public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case (MotionEvent.ACTION_DOWN) : // Touch screen pressed
case (MotionEvent.ACTION_UP) : // Touch screen touch ended
case (MotionEvent.ACTION_MOVE) : // Contact has moved across screen
case (MotionEvent.ACTION_CANCEL) : // Touch event cancelled
return super.onTouchEvent(event);
Now when you have a MapActivity you're tempted to do the same, however this won't work. The handler isn't being executed. I didn't find the exact reason for this behavior yet. Probably the reason is that the MapActivity doesn't automatically forward the event to the registered MapView or it just doesn't get notified about the event, since the motion event actually occurs on the MapView itself and not its parent, the MapActivity.

What can be done instead is to either register the event directly on the MapView
mapView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
..or to override the MapActivity's dispatchTouchEvent(MotionEvent). What has to be considered however is to appropriately forward the event in this case. For overriding event handlers, the Android API suggests to
Returns: True if the event was handled, false otherwise.
Now if you catch some touch event and you do your according processing, then you have to be aware that if you return true, the onTouch event won't be propagated, with the side-effect that the user won't be able to move on the map (or better "move the map on the screen"). Therefore, while in other cases you would return true after handling the event, in this specific case of the MapActivity you may consider not returning (or returning false) and just propagating the event by invoking super.dispatchTouchEvent(...).
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus