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
Categories: Tricks & Tips
click, coordinates, detect, tips, touch, tricks
Thanks nice code.
how would u send these x and y coordinates across a UDP datagrampacket
thanks
really nice one thanks a lot