[英]OnTouchEvent not working as intended in Android
the problem is is that the touchX and Y are not saving the value taken on ACTION.DOWN, how to keep this last values? 问题是touchX和Y没有保存ACTION.DOWN上获取的值,如何保留最后一个值? I wan to be able to draw a single line with coordinates from ACTION.DOWN to ACTION.U
我希望能够绘制从ACTION.DOWN到ACTION.U的坐标的单线
@Override
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float touchX = 0;// I've try = event.getX();
float touchY= 0;// = event.getY();
float upX = 0;// = event.getX();
float upY = 0;// = event.getX();
switch (event.getAction()) {
//case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
drawCanvas.drawText("x:"+ touchX + " ,y:"+ touchY,touchX, touchY, canvasPaint);
break;
case MotionEvent.ACTION_MOVE:
//skip
break;
case MotionEvent.ACTION_UP:
upX = event.getX();
upY = event.getY();
drawCanvas.drawText("x2:"+ touchX + " ,y2:"+ touchY,upX, upY, canvasPaint);
drawCanvas.drawLine(touchX, touchY, upX, upY, drawPaint);
//the problem is is that the touchX and Y are not saving the value taken on ACTION.DOWN, how to keep this last values?
break;
default:
return false;
}
invalidate();
return true;
}
If you want to save the values you must add the method variables as object attributes, if your method is just what you posted, you just need touchX
and touchY
: 如果要保存值,则必须将方法变量添加为对象属性,如果您的方法就是您发布的方法,
touchX
需要touchX
和touchY
:
public class YourView extends View {
// class attributes
float touchX = 0;
float touchY= 0;
@Override
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
switch (event.getAction()) {
// your logic using touchX and touchY now
// will keep values assigned here
}
}
}
If you need to use it more than once, you can create your own class to save coordinates: 如果需要多次使用它,则可以创建自己的类来保存坐标:
class MyPoint {
private float x;
private float y;
public MyPoint(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
@Override
public String toString() {
return "x:"+ x + " ,y:"+ y;
}
}
And use it like: 并像这样使用它:
public class YourView extends View {
// class attributes
private MyPoint touchPoint;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchPoint = new MyPoint(event.getX(), event.getY());
drawCanvas.drawText(touchPoint.toString(), canvasPaint);
break;
// more!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.