简体   繁体   中英

MotionEvent.Action_UP is always called

Here is the code for my onTouchEvent(MotionEvent event):

@Override
public boolean onTouchEvent(MotionEvent event){
    int action = event.getAction();
    int x = Math.round(event.getX());
    int y = Math.round(event.getY());
    //play is an imageView
    int viewLeft = play.getLeft();
    int viewRight = play.getRight();
    int viewTop = play.getTop();
    int viewBottom = play.getBottom();
    boolean onPoint = false;

    switch (action) {
        case MotionEvent.ACTION_DOWN:
            //Checks if the touched area falls within the imageView play
            if ((x >= viewLeft && x <= viewRight) && (y >= viewTop && y <= viewBottom)) {
                onPoint = true;
                play.setImageResource(R.drawable.playyellow);
            }
        case MotionEvent.ACTION_UP:
            //if the finger is lifed on the imageView, the intent is called
            play.setImageResource(R.drawable.play1);
            if (onPoint) {
                if ((x >= viewLeft && x <= viewRight) && (y >= viewTop && y <= viewBottom)) {
                    Intent i = new Intent(this, InGame.class);
                    startActivity(i);
                }
            }

    }
    return true;
}

The problem here is that ACTION_UP is always called, regardless of whether or not I actually lift my finger off the screen. I ran it in debugging mode while placing a breakpoint on case MotionEvent.ACTION_UP, and when I pressed down (and didn't release), it got called. Can someone explain why this happens?

I analyzed your code and I think it is just because you did not insert break in between Action_Down and Action_Up cases.

try the following code.....

switch (action) {
    case MotionEvent.ACTION_DOWN:
        //Checks if the touched area falls within the imageView play
        if ((x >= viewLeft && x <= viewRight) && (y >= viewTop && y <= viewBottom)) {
            onPoint = true;
            play.setImageResource(R.drawable.playyellow);
        }
         break;
    case MotionEvent.ACTION_UP:
        //if the finger is lifed on the imageView, the intent is called
        play.setImageResource(R.drawable.play1);
        if (onPoint) {
            if ((x >= viewLeft && x <= viewRight) && (y >= viewTop && y <= viewBottom)) {
                Intent i = new Intent(this, InGame.class);
                startActivity(i);
            }
        }

}
return true;

I hope it will help you...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM