栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/164768.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号