定义一个小球,使其在View的Canvas中水平往返移动,当小球触碰到右边边界时往左移动,小球触碰到左边边界时往右移动,循环往复。
view文件:
public class BallMoveView extends View {
private int X;
private int Y = 100;
private int radius = 30;
private Paint mPaint;
private boolean flag;//移动方向 true为右边,false为左边
public BallMoveView(Context context, AttributeSet attrs) {
super(context, attrs);
//参数表示去锯齿
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.RED);//小球的颜色
X = radius;
}
//该方法用于组件的绘图
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();//获得屏幕宽
//int width = this.getMeasuredWidth();
canvas.drawCircle(X, Y, radius, mPaint);
if (X < radius) {
flag = true;
} else if (X > (width - radius)) {
flag = false;
}
//改变x坐标,当线程调用invalidate()方法后
X = flag ? X + 5 : X - 5;//每次位移五个像素点
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<com.bingo.myTest.BallMoveView
android:id="@+id/moveView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
在Activity中调用:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
ballMoveView.postInvalidate();
}
},250,50);
效果图: