我的屏幕上有一个图像(ImageView)。图像占据屏幕的大约一半,这意味着您可以单击图像和图像侧面。
点击图片后如何在屏幕上显示x和y坐标?
我尝试使用onTouchEvent但只在我点击图片外部时调用,而不是在我点击图片时调用。
此致 的Mattias
答案 0 :(得分:5)
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
});
此外,我的this answer也很有用。
答案 1 :(得分:2)
我最终没有在ImageView上设置任何OnClickListener。相反,我只实现“public void onTouch(MotionEvent event)”和“public void onWindowFocusChanged(boolean hasFocus)”,如下所示:
private int fieldImgXY[] = new int[2];
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Use onWindowFocusChanged to get the placement of
// the image because we have to wait until the image
// has actually been placed on the screen before we
// get the coordinates. That makes it impossible to
// do in onCreate, that would just give us (0, 0).
fieldImage.getLocationOnScreen(fieldImgXY);
Log.i(LOG_TAG, "fieldImage lockation on screen: " +
xyString(fieldImgXY[0], fieldImgXY[1]));
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.i(LOG_TAG, "touch event - down");
int eventX = (int) event.getX();
int eventY = (int) event.getY();
Log.i(LOG_TAG, "event (x, y) = " + xyString(eventX, eventY));
int xOnField = eventX - fieldImgXY[0];
int yOnField = eventY - fieldImgXY[1];
Log.i(LOG_TAG, "on field (x, y) = " + xyString(xOnField, yOnField));
}
return super.onTouchEvent(event);
}
答案 2 :(得分:0)
使用ImageView上的OnClickListener接收点击事件,或者从ImageView抽象出类,并覆盖函数“public void onTouch(MotionEvent evt)”以从此视图中获取X / Y坐标。
答案 3 :(得分:0)
imageview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
}
return false;
}
});