利用Handler来更新android的UI (2)

利用Handler来更新android的UI (2)

文字程序很简单,一个View,一个Activity,利用handler和postInvalidate()更新UI。

程序效果是一个蓝色的正方形向右移出屏幕。

package com.ray.test;

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 TestHandler 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(update);
        setContentView(myView);
    }
   
    private Runnable update = new Runnable() {
        public void run() {
            myView.update();
            mHandler.postDelayed(update, 5);
        }
    };
   
    class MyView extends View{
   
    private float x = 0f;
public MyView(Context context) {
super(context);

}

public void update(){
postInvalidate();
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
x+=1;
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
canvas.drawRect(x, 40, x+40, 80, mPaint);
}
   
    }

你可能感兴趣的:(android,UI,OS)