I have a button and want to use a LongClickListener, to get by pressing on the button the coordinates during changing the position of the button. How can I get in a LongClickListener or perhaps other Method the X,Y coordinates of the Click/Mouse.
I tried it with an OnTouchListener, that is working. But the problem is that the TouchListener reacts on each click and not how I want only on pressed.
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;
}
};
You have to store the last known coordinates as found in onTouch somewhere (global data for example) and read them in your onLongClick method.
You may also have to use onInterceptTouchEvent in some cases.
The solution is to
OnTouchListener
OnLongClickListener
The other two answers leave out some details that might be helpful, so here is a full 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;
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With