Home > Tricks & Tips > Detect XY-coordinates when clicking or touching on screen

Detect XY-coordinates when clicking or touching on screen


If you want to get the XY-coordinates when users click on screen, the implementation of OnClickListener won’t do it. However, you need to override the onTouchEvent(), this will do the trick.

package pete.android.study;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

public class MainActivity extends Activity  {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// MotionEvent object holds X-Y values
		if(event.getAction() == MotionEvent.ACTION_DOWN) {
			String text = "You click at x = " + event.getX() + " and y = " + event.getY();
			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		return super.onTouchEvent(event);
	}
}

Hope you enjoy it!

Cheers,
Pete Houston

About these ads
  1. Ajay Prasad
    February 8, 2014 at 4:39 pm | #1

    Hi Pete Houston,
    really nice code, can you explain how we set this function on imageview only.

    please tell me on ajayprasad.java@gmail.com

    Thanks,

  2. murthy
    February 23, 2013 at 8:22 pm | #2

    Thanks nice code.

  3. March 30, 2012 at 1:34 am | #3

    how would u send these x and y coordinates across a UDP datagrampacket

  4. durgesh
    February 3, 2012 at 7:36 pm | #4

    thanks

  5. durgesh
    February 3, 2012 at 6:29 pm | #5

    really nice one thanks a lot

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: