[英]Android View Canvas onTouchEvent
我正在尝试做一个愚蠢的应用程序,其中使用Canvas
绘制的“ HelloWorld!!
”字符串移动。 字符串的位置(x_new, y_new)
只是它的旧位置(x_old, y_old)
加上ACTION_UP
事件返回的(x, y)
。 问题是事件ACTION_UP
无法识别。 Log.d()
函数总是打印像motionEvent(28254): MotionEvent{4050df70 action=4 x=354.0 y=415.0 pressure=0.20000002 size=0.26666668}
其中action=4
永远不会改变。 你有什么建议吗? 谢谢!!
class myView extends View {
private Canvas canvas;
private int x;
private int y;
public HUDView(Context context) {
super(context);
this.x=5;
this.y=5;
}
protected void onDraw(Canvas canvas) {
this.canvas=canvas;
this.canvas.drawText("HelloWorld!!", x, y, mLoadPaint);
}
@Override
public boolean onTouchEvent( MotionEvent event) {
super.onTouchEvent(event);
Log.d("motionEvent", event.toString());
if (event.getAction()==MotionEvent.ACTION_UP){
Log.d("motionEvent", "action_up");
this.x+=(int)event.getX();
this.y+=(int)event.getY();
return true;
}
this.postInvalidate();
return true;
}
}
不需要全局变量Canvas(您在不使用视图更新的画布上绘图)
在onTouchEven中如果Action已启动,则返回true而不使用postInvalidating
您的构造函数名称错误
因为它代表你的代码不会运行的问题。 这应该工作
class myView extends View {
private int x;
private int y;
public myView (Context context) {
super(context);
this.x=5;
this.y=5;
}
@Override
protected void onDraw(Canvas canvas){
canvas.drawText("HelloWorld!!", x, y, mLoadPaint);
}
@Override
public boolean onTouchEvent( MotionEvent event) {
super.onTouchEvent(event);
Log.d ("motionEvent", event.toString());
if (event.getAction()==MotionEvent.ACTION_UP){
Log.d("motionEvent", "action_up");
this.x+=(int)event.getX();
this.y+=(int)event.getY();
}
this.postInvalidate();
return true;
}
}
使用invalidate post invalidate用于线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.