onTouchEvent executes twice
Asked Answered
A

2

20

Can anyone explain to me why is the onTouchEvent executed twice and how can I set it to run only once? I couldn't find an explanation. Thanks.

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    _iv = new ImageView(this);

    _map = BitmapFactory.decodeResource(getResources(), R.drawable.image);

        _iv.setImageBitmap(_map);
        _iv.invalidate();

    setContentView(_iv);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    double X = event.getX();
    double Y = event.getY();

    Toast.makeText(this, "X: " + X + " Y: " + Y, Toast.LENGTH_SHORT).show();

    return super.onTouchEvent(event);
}
Airboat answered 3/10, 2011 at 21:23 Comment(0)
S
39

It executes for every event. In this case it would be for the ACTION_DOWN and ACTION_UP event. It will also execute for the ACTION_MOVE event many, many times.

To have it only execute in one event, do something like this:

switch(event.getAction())
{
  case MotionEvent.ACTION_DOWN:
    ** CODE ** 
    break;
  case MotionEvent.ACTION_MOVE:
    ** CODE ** 
    break;
  case MotionEvent.ACTION_UP:
    ** CODE **
    break;
}
Sprag answered 3/10, 2011 at 21:28 Comment(2)
Hi Deev, I used onTouchEvent for placing marker on touch of map. But i found that onTOuchEvent method is called multiple times. I used the same switch case as described here. But still my method gets called multiple times. Can you please suggest me why this is happeningPhenacetin
Android generally cascades onTouchEvents down views until one of them returns "true". Return "true" if your touch event has been fully handled and it should stop.Sprag
E
-2

In the switch statement, return false for all the events you do not need.

Equipollent answered 3/1, 2017 at 21:3 Comment(1)
Add example similar to what the previous poster did? Otherwise, this comments adds nothing.Fulk

© 2022 - 2024 — McMap. All rights reserved.