我创建了一个弹跳球的动画(通过下面的代码)。
我想知道如何在特定条件下停止此动画,例如10秒后或当球到达特定坐标时。
代码:
public class MyDemoView extends ImageView{
private Context mContext;
int x = -1;
int y = -1;
private int xVelocity = 10;
private int yVelocity = 5;
private Handler h;
private final int FRAME_RATE = 30;
public MyDemoView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = new Runnable() {
@Override
public void run() {
invalidate();
}
};
protected void onDraw(Canvas c) {
BitmapDrawable ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.ball);
if (x<0 && y <0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
} else {
x += xVelocity;
y += yVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
xVelocity = xVelocity*-1;
}
if ((y > this.getHeight() - ball.getBitmap().getHeight()) || (y < 0)) {
yVelocity = yVelocity*-1;
}
}
c.drawBitmap(ball.getBitmap(), x2, y2, null);
h.postDelayed(r, FRAME_RATE);
}
}
答案 0 :(得分:1)
要停止动画,请使用以下代码:
object.clearAnimation();
或
animation.cancel();
后者可能不适用于2.1,不记得。
答案 1 :(得分:0)
根据您的代码,只需致电h.removeCallbacks(r)
?