[英]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.