OnClickListener-x,y 事件位置?

我有一个自定义视图派生自查看。当单击视图时,我希望得到通知,以及单击发生的位置的 x,y 位置。长点击也一样。

看起来要这么做,我需要重写 onTouchEvent()。但是有没有办法从 OnClickListener中获得事件的 x,y 位置呢?

如果没有,什么是一个很好的方法来判断一个运动事件是一个“真正的”点击还是一个长点击等?onTouchEvent产生许多快速连续的事件等。

71002 次浏览

Override onTouchEvent(MotionEvent ev)

Then you can do:

ev.getXLocation()

Or something like that. Have a butches.

Thank you. That was exactly what I was looking for. My code now 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;
}
});

which does precisely what Mark asked for...

Full example

The other answers are missing some details. Here is a full 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 the coordinates
  • Save the X,Y coordinates using an OnTouchListener
  • Access the X,Y coordinates in the OnClickListener

You can make an extension function in Kotlin, like this:

fun View.setOnClickListenerWithPoint(action: (Point) -> Unit) {
val coordinates = Point()
val screenPosition = IntArray(2)
setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
v.getLocationOnScreen(screenPosition)
coordinates.set(event.x.toInt() + screenPosition[0], event.y.toInt() + screenPosition[1])
}
false
}
setOnClickListener {
action.invoke(coordinates)
}
}

If you need a long click - just replace setOnClickListener

I use getLocationOnScreen() because I need coordinates for RecyclerView's ViewHolder