Create Project
This app implements the animation that looks like the ball is rolling. First, create a new project.
- Type "Ball" to [Application name], and click [Next]
Create the "Ball" Class
Then, create a class of ball rolling in the screen. "Ball" has radius and coordinates that indicate the position in the screen as member variables. In addition, "Ball" also has method to draw itself to the screen.
package com.example.ball;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
int x, y, radius;
Paint paint;
public Ball(Context context) {
super(context);
radius = 30;
x = y = 0;
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawCircle(x, y, radius, paint);
}
}
Implementation of Animation
To achieve the animation will implement the Runnable interface to MainActivity.
- Rewrite the "MainActivity.java" to the source code of the following
package com.example.ball;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
public class MainActivity extends Activity implements Runnable {
Ball ball;
Handler handler;
int width, height;
int dx = 10, dy = 10, time = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
RelativeLayout relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundColor(Color.GREEN);
setContentView(relativeLayout);
handler = new Handler();
handler.postDelayed(this, time);
WindowManager windowManager =
(WindowManager)getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
width = point.x;
height = point.y;
ball = new Ball(this);
ball.x = width / 2;
ball.y = height / 2;
relativeLayout.addView(ball);
}
@Override
public void run() {
ball.x += dx;
ball.y += dy;
if (ball.x <= ball.radius) {
ball.x = ball.radius;
dx = -dx;
} else if (ball.x >= width - ball.radius) {
ball.x = width - ball.radius;
dx = -dx;
}
if (ball.y <= ball.radius) {
ball.y = ball.radius;
dy = -dy;
} else if (ball.y >= height - ball.radius) {
ball.y = height - ball.radius;
dy = -dy;
}
ball.invalidate();
handler.postDelayed(this, time);
}
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(this);
}
}
When you run the app, you can find an animation that looks like a golf ball rolling on lawn. Rebounding at the edge of the screen and keep rolling can also be confirmed.
0 件のコメント:
コメントを投稿