其实文字游戏程序很简单,就是一个view和一个Activity,在利用下handier和postInvalidate()更新UI 调用Handler.post(Runnable
其实文字游戏程序很简单,就是一个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();
}
}
}
}
--结束END--
本文标题: android开发教程之handler异步更新ui
本文链接: https://lsjlt.com/news/27189.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0