Joe S Joe S - 23 days ago 8
Java Question

android - stop animation

In my program an image is animated vertically. I'd like the animation to stop at the right margin. I think the condtion in the second if-sequence should say that, but how do i stop the invalidate() method to animate at that point?

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) {
x = this.getWidth()/2;
y = this.getHeight()/3;
}

else {
x += xVelocity;

if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {





}
}

c.drawBitmap(ball.getBitmap(), x, y, null);

h.postDelayed(r, FRAME_RATE);


}
}

Answer

Use h.postDelayed(r, FRAME_RATE); only if you want to continue the animation.

One way to achieve this is with a boolean (let's call it continueAnimation) which you set depending on the position of the animated item. Then you can write

c.drawBitmap(ball.getBitmap(), x, y, null);  
if ( continueAnimation )
   {
       h.postDelayed(r, FRAME_RATE);
   }