0

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?

2 Answers2

0

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.

Farshad
  • 3,074
  • 2
  • 30
  • 44
  • Tried that too, But I still cant understand what is "event" and how would I pass "event" in onTouchEvent() while calling the function?? – user5714576 Jan 26 '16 at 22:03
  • You don't provide the event, it's provided by the Android touch system. You just need to make sure you have a view on screen that can pick up the touch events. – ootinii Jan 26 '16 at 22:08
  • As I said before events make your activity call a specific method which handles that event, By default your activity has a onTouchEvent , All you need is to override it how you want, got it ? – Farshad Jan 26 '16 at 22:08
0

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.

  • This is only if FarShaD answer does not work, I see nothing wrong with his, but if it doesn't work for whatever reason give this a try. –  Nov 28 '16 at 18:51