定義一個小球,使其在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);
效果圖: