OnClickListener - x, y event location?

I have a custom view derived from a view. I want to be notified when the image is clicked, and the location x, y where the click occurred. The same goes for long clicks.

It looks like I need to override onTouchEvent() . Is there no way to get the x, y location of the event from the OnClickListener instead?

If not, what good way to tell if a motion event is a β€œreal” click and a long click, etc.? onTouchEvent generates many events in quick succession, etc.

+59
android
Dec 27 '09 at 21:03
source share
3 answers

Thank. This is exactly what I was looking for. Now my code is:

 imageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY())); } return true; } }); 

who does exactly what Mark asked for ...

+71
Oct 26 '10 at 11:48
source share

Override onTouchEvent (MotionEvent ev)

Then you can do:

 ev.getXLocation() 

Or something like that. Have the balls.

+3
Dec 27 '09 at 21:06
source share

Full example

Other answers are missing some details. Here is a complete example.

 public class MainActivity extends AppCompatActivity { // class member variable to save the X,Y coordinates private float[] lastTouchDownXY = new float[2]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // add both a touch listener and a click listener View myView = findViewById(R.id.my_view); myView.setOnTouchListener(touchListener); myView.setOnClickListener(clickListener); } // the purpose of the touch listener is just to store the touch X,Y coordinates View.OnTouchListener touchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // save the X,Y coordinates if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { lastTouchDownXY[0] = event.getX(); lastTouchDownXY[1] = event.getY(); } // let the touch event pass on to whoever needs it return false; } }; View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { // retrieve the stored coordinates float x = lastTouchDownXY[0]; float y = lastTouchDownXY[1]; // use the coordinates for whatever Log.i("TAG", "onLongClick: x = " + x + ", y = " + y); } }; } 

Summary

  • Add a class variable to store coordinates
  • Save X, Y coordinates with OnTouchListener
  • Access X, Y coordinates in OnClickListener
+3
Oct 07 '17 at 11:07 on
source share



All Articles