当前位置: 移动技术网 > IT编程>移动开发>Android > Android中invalidate()和postInvalidate() 的区别及使用方法

Android中invalidate()和postInvalidate() 的区别及使用方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

camgoo,大主宰域名交易平台,好好先生迅雷下载

android中实现view的更新有两组方法,一组是invalidate,另一组是postinvalidate,其中前者是在ui线程自身中使用,而后者在非ui线程中使用。

      android提供了invalidate方法实现界面刷新,但是invalidate不能直接在线程中调用,因为他是违背了单线程模型:android ui操作并不是线程安全的,并且这些操作必须在ui线程中调用。

  invalidate()是用来刷新view的,必须是在ui线程中进行工作。比如在修改某个view的显示时,调用invalidate()才能看到重新绘制的界面。invalidate()的调用是把之前的旧的view从主ui线程队列中pop掉。 一个android 程序默认情况下也只有一个进程,但一个进程下却可以有许多个线程。

  在这么多线程当中,把主要是负责控制ui界面的显示、更新和控件交互的线程称为ui线程,由于oncreate()方法是由ui线程执行的,所以也可以把ui线程理解为主线程。其余的线程可以理解为工作者线程。

  invalidate()得在ui线程中被调动,在工作者线程中可以通过handler来通知ui线程进行界面更新;而postinvalidate()在工作者线程中被调用。

利用invalidate()刷新界面

  实例化一个handler对象,并重写handlemessage方法调用invalidate()实现界面刷新;而在线程中通过sendmessage发送界面更新消息。

// 在oncreate()中开启线程 
new thread( new gamethread()).start();、 
// 实例化一个handler 
handler 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(); 
} 
} 
} 
} 
// 在oncreate()中开启线程
new thread(new gamethread()).start();、
// 实例化一个handler
handler 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()刷新界面

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

以上所述是小编给大家分享的android中invalidate()和postinvalidate() 的区别及使用方法,希望对大家有所帮助!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网