开发者

onTouchEvent executes twice

开发者 https://www.devze.com 2023-04-10 02:59 出处:网络
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.

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);
}


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消