I’m new to android and I’m having problems understanding how to animate canvas.
basically i have drawn a red ball and a stair when the ball should drop from the stair
here’s what it looks like.

can anyone help me on what method i should use? if you can provide me with a source code that would be very helpful.
here are my source code:
DrawingView.java
package com.ballandstair;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
public class DrawingView extends View {
DrawingView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint paint = new Paint();
Path path = new Path();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
canvas.drawCircle(100, 50, 25, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);
path.moveTo(75, 75);
path.lineTo(125, 75);
path.lineTo(125, 125);
path.lineTo(175, 125);
path.lineTo(175, 175);
path.lineTo(225, 175);
path.lineTo(225, 225);
path.lineTo(275, 225);
path.lineTo(275, 275);
path.lineTo(325, 275);
path.lineTo(325, 325);
path.lineTo(75, 325);
path.close();
canvas.drawPath(path, paint);
}
}
MainActivity.java
package com.ballandstair;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DrawingView drawing = new DrawingView(this);
setContentView(drawing);
}
}
You will need to do (at least) two things:
The second step requires a little care. You might be tempted to write a loop that invokes
Thread.sleep(frameRate)(whereframeRateis the number of milliseconds between frames), updates the ball position, and then callsinvalidate()for your custom view to trigger a repaint. The problem with this is that you cannot pause the event thread. There are (again) two ways of dealing with this:invalidate()directly, but it can callpostInvalidate()to the same effect.Runnablethat in itsrun()method updates the ball position, callsinvalidate(), and then asks the view to run theRunnableitself again after a delay offrameRate(by callingpostDelayed()).Both methods are reasonable approaches. You will also need logic to know when the animation should end, and you might want to give the user control over when it starts or to allow replay.