android之使用handler异步更新ui的示例
其实文字游戏程序很简单,就是一个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();
}
}
}
}
如果你对android之使用handler异步更新ui的示例文章还有不了解的地方,那就来网站跟小编交流,我们每天都会提供各种文章内容,方便日后你们有需要的时候可以翻阅。