android学习之通过handler更新UI的例子
通过handler来更新UI:
package com.myandroid.handler;
import android.app.Activity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class HandlerViewActivity extends Activity {
private MyView myView;
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this);
mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
myView.invalidate();
mHandler.postDelayed(this, 5);
}
});www.zzzyk.com
setContentView(myView);
}
class MyView extends View {
private float x = 0f;
public MyView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
x += 1;
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
canvas.drawRect(x, 40, x + 20, 48, mPaint);
canvas.drawRect(x, 54, x + 20, 62, mPaint);
canvas.drawCircle(x+10, 51, 6, mPaint);
canvas.drawRect(x+10, 50, x + 20, 52, mPaint);
mPaint.setColor(Color.RED);
canvas.drawRect(x, 80, x + 20, 88, mPaint);
canvas.drawRect(x, 94, x + 20, 102, mPaint);
canvas.drawCircle(x+10, 91, 6, mPaint);
canvas.drawRect(x+10, 90, x + 20, 92, mPaint);
mPaint.setColor(Color.YELLOW);
canvas.drawRect(x, 120, x + 20, 128, mPaint);
canvas.drawRect(x, 134, x + 20, 142, mPaint);
canvas.drawCircle(x+10, 131, 6, mPaint);
canvas.drawRect(x+10, 130, x + 20, 132, mPaint);
mPaint.setColor(Color.GREEN);
canvas.drawRect(x, 160, x + 20, 168, mPaint);
canvas.drawRect(x, 174, x + 20, 182, mPaint);
canvas.drawCircle(x+10, 171, 6, mPaint);
canvas.drawRect(x+10, 170, x + 20, 172, mPaint);
}
}
}
运行起来后看到有4个小坦克从左向右移动:
补充:移动开发 , Android ,