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();
}
}
}
}