I have a class with animation on the canvas. I need to handle touching, but OnTouchListener doesn't work. I tried to put a listener to main activity, but it didn't work anyway.
public class Animation extends View implements View.OnTouchListener{
private Paint paint;
private Snake snake;
public Animation(Context context) {
super(context);
snake = new Snake(10, 10, 1, 0, 1, 50);
paint = new Paint();
paint.setColor(Color.BLACK);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
snake.move(canvas);
invalidate();
}
public boolean onTouch(View v, MotionEvent event) {
System.out.println("asfaf");
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println(x + ' ' + y);
break;
case MotionEvent.ACTION_MOVE:
System.out.println(x + ' ' + y);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
System.out.println(x + ' ' + y);
break;
}
return true;
}
}
Replace your onTouch()
method with onTouchEvent()
.
@Override
public boolean onTouchEvent(MotionEvent event) {
System.out.println("asfaf");
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println(x + ' ' + y);
break;
case MotionEvent.ACTION_MOVE:
System.out.println(x + ' ' + y);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
System.out.println(x + ' ' + y);
break;
}
return true;
}
and remove implements View.OnTouchListener
.
删除implements View.OnTouchListener
从你的类,并把一个@Override
在你onTouchEvent()
方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.