android开发教程之handler异步更新ui_安卓软件开发教程-查字典教程网
android开发教程之handler异步更新ui
android开发教程之handler异步更新ui
发布时间:2016-12-28 来源:查字典编辑
摘要:其实文字游戏程序很简单,就是一个view和一个Activity,在利用下handier和postInvalidate()更新UI调用Hand...

其实文字游戏程序很简单,就是一个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();

}

}

}

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新安卓软件开发学习
    热门安卓软件开发学习
    编程开发子分类