当前位置: 移动技术网 > IT编程>移动开发>Android > android中Invalidate和postInvalidate的更新view区别

android中Invalidate和postInvalidate的更新view区别

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

尉劼,活效株,仙人掌搜索引擎

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

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

android程序中可以使用的界面刷新方法有两种,分别是利用invalidate和利用postinvalidate()来实现在线程中刷新界面。

1,利用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();
}
}
}
}

2,使用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();
}
}
}
view 类中postinvalidate()方法源码如下,可见它也是用到了handler的:
public void postinvalidate() {
postinvalidatedelayed(0);
}

public void postinvalidatedelayed(long delaymilliseconds) {
// we try only with the attachinfo because there's no point in invalidating
// if we are not attached to our window
if (mattachinfo != null) {
message msg = message.obtain();
msg.what = attachinfo.invalidate_msg;
msg.obj = this;
mattachinfo.mhandler.sendmessagedelayed(msg, delaymilliseconds);
}
}

除了oncreate()不是运行在ui线程上的,其实其他大部分方法都是运行在ui线程上的,其实只要你没有开启新的线程,你的代码基本上都运行在ui线程上。

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

相关文章:

验证码:
移动技术网