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. */
    public void onCreate(Bundle savedInstanceState) {

	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!

Pete Houston

  1. May 7, 2018 at 2:56 pm

    should i need to do some plugin

  2. Vin
    September 8, 2016 at 8:04 pm

    Thanks for a simple and nice code for beginners like me. It helped a lot.

  3. Ajay Prasad
    February 8, 2014 at 4:39 pm

    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


  4. murthy
    February 23, 2013 at 8:22 pm

    Thanks nice code.

  5. March 30, 2012 at 1:34 am

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

  6. durgesh
    February 3, 2012 at 7:36 pm


  7. durgesh
    February 3, 2012 at 6:29 pm

    really nice one thanks a lot

  1. No trackbacks yet.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: