Android Click LongClickListener to get X, Y, OnTouchListener coordinates

I have a button and you want to use the LongClickListener to get a click on the coordinate button when the button is positioned. How can I get in LongClickListener or possibly another X, Y method Click / Mouse coordinates.

I tried it using OnTouchListener, which works. But the problem is that TouchListener responds to every click, and not to the way I want only when clicked.

+6
source share
4 answers

Do it like here in OnTouchListener:

OnTouchListener mOnTouch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final int x = (int) ev.getX(); final int y = (int) ev.getY(); break; } }; 
+11
source

You have to save the last known coordinates found in onTouch somewhere (for example, global data) and read them in the onLongClick method.

In some cases, you may also need to use onInterceptTouchEvent .

+4
source

Decision -

  • Add a class variable to store coordinates
  • Save X, Y coordinates with OnTouchListener
  • Access X, Y coordinates in OnLongClickListener

The other two answers lack some details that might be useful, so here is a complete demonstration:

 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 long click listener View myView = findViewById(R.id.my_view); myView.setOnTouchListener(touchListener); myView.setOnLongClickListener(longClickListener); } // 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.OnLongClickListener longClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(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); // we have consumed the touch event return true; } }; } 
+1
source
 @Override public boolean performLongClick(float x, float y) { super.performLongClick(x, y); doSomething(); return super.performLongClick(x, y); } 
0
source

Source: https://habr.com/ru/post/891696/


All Articles