简体   繁体   中英

Can I get coordinates x y of the position where I tap? OnTapListener?

I've been searching for some function that can give me x,y coordinates of the the point where I touch on screen. I got a code of onTouch() but couldn't find a way to call that function.

public boolean onTouch(View v, MotionEvent event) {
   int x = event.getX();
   int y = event.getY();
   return true;
}

What is View and MotionEvent that I'm supposed to pass in arguements? Can anyone please help me and tell me how to get just x,y of the point of touch?

Try this for a view:

View yourView = findViewById(R.id.yourViewId)
    yourView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            // Do something
            x = event.getX();
            y = event.getY();
            }
            return true;
        }
    });

or Try this for an activity:

@Override
public boolean onTouchEvent(MotionEvent event) {
            if(event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            // Do something
            x = event.getX();
            y = event.getY();
            }
            return true;
}

By the way, you don't need to call this method, you just override it and any time the screen is touched, this method will be called by your activity.

Let me know if this doesn't work and I'll delete the answer

To get the coordinates for when you press try:

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: // when you touch
        x = event.getRawX(); // gather x and y
        y = event.getRawY();
        break;

PS I would comment but have too low rep PSS you if statement if this is all you want to do, switch if your trying to do multiple things ie dragging an item.

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