Android Press LongClickListener获取X,Y坐标,OnTouchListener
我有一个按钮,想使用LongClickListener,在改变按钮位置的过程中,通过按下按钮获得坐标。如何在LongClickListener或其他方法中获取单击/鼠标的X、Y坐标Android Press LongClickListener获取X,Y坐标,OnTouchListener,android,Android,我有一个按钮,想使用LongClickListener,在改变按钮位置的过程中,通过按下按钮获得坐标。如何在LongClickListener或其他方法中获取单击/鼠标的X、Y坐标 我用一个听者试了一下,效果不错。但问题是TouchListener在每次单击时都会做出反应,而不是我只想在按下按钮时做出的反应。在OnTouchListener中这样做: OnTouchListener mOnTouch = new OnTouchListener() { @Override publ
我用一个听者试了一下,效果不错。但问题是TouchListener在每次单击时都会做出反应,而不是我只想在按下按钮时做出的反应。在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;
}
};
您必须将在onTouch中找到的最后一个已知坐标存储在某处(例如全局数据),并在onLongClick方法中读取它们 在某些情况下,您可能还必须使用onInterceptTouchEvent
- 添加一个类变量来存储坐标
- 使用
OnTouchListener保存X,Y坐标
- 访问
OnLongClickListener中的X,Y坐标
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;
}
};
}
不,那不是我想要的。我不想每次点击都按下在你的OnLongClickListener@RichardOnLongClickListener在其回调中不提供坐标
@Override
public boolean performLongClick(float x, float y) {
super.performLongClick(x, y);
doSomething();
return super.performLongClick(x, y);
}