简体   繁体   中英

How to use OnTouchListener to keep track of ACTION_DOWN and ACTION_UP (x,y) coordinates?

I'm new to android studio. In my app I have a button where I want to get the x-coord and y-coord of both where the button is clicked and released. I put the following code in the onCreate() method and I'm not sure where to go from here.

btn1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            float x1,x2,y1,y2;
            switch(event.getAction()){
                case(MotionEvent.ACTION_DOWN):{
                    x1 = event.getX();
                    y1 = event.getY();
                    Log.d("Pressed 1", "x1=" + x1 + "y1=" + y1);
                    break;
                }
                case(MotionEvent.ACTION_UP):
                    y2=event.getY();
                    Log.d("Released 1", "x2=" + x2 + "y2=" + y2);

            }
            return false;
        }
    });

You should return true , or the following MotionEvent will not going to this onTouch callback.

If you need the moving event, case MotionEvent.ACTION_MOVE also.

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