自定义View (不应写布局)
-
Pview.java
public class Pview extends View {
private int cirx = 20, ciry = 20; // 圆心点
private int radius = 20; // 半径
private int rectx = 100, recty = 400;
private int dirx, diry; // 方向0正方向 , 1反方向
private Timer mTimer = new Timer(); // 定时器
private int width, height;
private Paint mPaint;
//布局发生变化时的回调函数,间接回去调用onMeasure, onLayout函数重新布局
@Override
protected void onSizeChanged(int w, int h, int oldl, int oldt) {
super.onSizeChanged(w, h, oldl, oldt);
width = w;
height = h;
}
public Pview(Context context) {
super(context);
// 设置聚焦
setFocusable(true);
// 图形的绘制,运动方向
// 自由任务交给定时任务去做
TimerTask mTask = new TimerTask() {
@Override
public void run() {
// 绘制圆的运动方向(自由匀速)
if (dirx == 0) {
cirx += 5;
}
if (dirx == 1) {
cirx -= 5;
}
if (diry == 0) {
ciry += 5;
}
if (diry == 1) {
ciry -= 5;
}
// 修改运动方向
// 最右边
if (cirx + radius > width) {
dirx = 1;
}
// 最左边
if (cirx - radius < 0) {
dirx = 0;
}
// 最下边
if (ciry + radius > height) {
diry = 1;
}
// 最上边
if (ciry - radius < 0) {
diry = 0;
}
// 球碰到矩形也要更改方向
if (cirx > rectx && cirx < rectx + 300) {
if (ciry + radius > recty) {
diry = 1;// 往上走
}
// if (ciry - radius < recty) {
// diry = 0;// 往下走
// }
}
postInvalidate();// 进行实时刷新
}
};
// 把任务加到计时器里面去
mTimer.schedule(mTask, 1, 20);
}
// 绘制图形
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint = new Paint();
mPaint.setColor(Color.RED);
canvas.drawCircle(cirx, ciry, radius, mPaint);// 画圆
mPaint.setColor(Color.BLACK);
canvas.drawRect(rectx, recty, rectx + 300, recty + 2, mPaint);// 画矩形
}
//控制板上下移动
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
recty+=15;
break;
case KeyEvent.KEYCODE_DPAD_UP:
recty-=15;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
rectx-=15;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
rectx+=15;
break;
default:
break;
}
return true;
}
}
-
MainActivity.java(引用View)
public class MainActivity extends Activity {
private Pview mPview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
mPview = new Pview(this);
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
setContentView(mPview);
mPview.requestFocus();
}
}
-
演示
网友评论