Android界面刷新

来源:互联网 发布:office fix it 2007 编辑:程序博客网 时间:2024/06/05 14:24

Android的invalidate与postInvalidate都是用来刷新界面的,用法区别在于:

invalidate():只可在主线程中使用。实例化一个Handler对象,并重写handleMessage方法调用invalidate()实现界面刷新;而在线程中通过sendMessage发送界面更新消息。

// 在onCreate()中开启线程new Thread(new GameThread()).start();// 实例化一个handlerHandler myHandler = new Handler() {// 接收到消息后处理public void handleMessage(Message msg) {switch (msg.what) {case Activity01.REFRESH:mGameView.invalidate(); // 刷新界面break;}super.handleMessage(msg);}};class GameThread implements Runnable {public void run() {while (!Thread.currentThread().isInterrupted()) {Message message = new Message();message.what = Activity01.REFRESH;// 发送消息Activity01.this.myHandler.sendMessage(message);try {Thread.sleep(100);} catch (InterruptedException e) {Thread.currentThread().interrupt();    }}}}

使用postInvalidate则比较简单,可在任何线程中使用。不需要handler,直接在线程中调用postInvalidate即可。

class GameThread implements Runnable {public void run() {while (!Thread.currentThread().isInterrupted()) {try {Thread.sleep(100);} catch (InterruptedException e) {Thread.currentThread().interrupt();    }// 使用postInvalidate可以直接在线程中更新界面mGameView.postInvalidate();}}}

转自:http://www.cnblogs.com/devinzhang/archive/2012/01/28/2330468.html

0 0
原创粉丝点击