android开发教程之handler异步更新ui

时间:2022-05-17 03:41:54

其实文字游戏程序很简单,就是一个view和一个Activity,在利用下handier和postInvalidate()更新UI

调用Handler.post(Runnable r)方法,Runnable运行在UI所在线程,所以可以直接调用View.invalidate()

复制代码 代码如下:


packagecom.Test.androidtest;

 

importandroid.app.Activity;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;

publicclassTestHandlerextendsActivity{
privateMyViewmyView;
privateHandlermHandler;
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
myView=newMyView(this);
mHandler=newHandler();
mHandler.post(newRunnable(){
@Override
publicvoidrun(){
myView.invalidate();
mHandler.postDelayed(this,5);
}
});
setContentView(myView);27}

classMyViewextendsView{30privatefloatx=0f;31publicMyView(Contextcontext){
super(context);33
}
protectedvoidonDraw(Canvascanvas){
super.onDraw(canvas);37x+=1;
PaintmPaint=newPaint();
mPaint.setColor(Color.BLUE);
canvas.drawRect(x,
,x+40,80,mPaint);41}

}
}

 

在新线程里更新UI,可以直接postInvalidate()

 

复制代码 代码如下:


publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

 

myView=newMyView(this);
this.setContentView(this.myView);
newThread(newmyThread()).start();
}

classmyThreadimplementsRunnable{
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
try{
myView.postInvalidate();
Thread.sleep(100);
}catch(InterruptedExceptione){
Thread.currentThread().interrupt();
}
}
}
}