设为首页 加入收藏

TOP

Android中实现view的更新UI有两组方法的问题
2014-11-24 03:00:55 来源: 作者: 【 】 浏览:2
Tags:Android 实现 view 更新 方法 问题

一组是invalidate,另一组是postInvalidate,其中前者是在UI线程自身中使用,而后者在非UI线程中使用。


SDK中说:


public void invalidate()
Invalidate the whole view. If the view is visible, onDraw(Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().


public void postInvalidate ()
Cause an invalidate to happen on a subsequent cycle through the event loop. Use this to invalidate the View from a non-UI thread.


google的文档的说明实在是简单,往往看了开发中都会遇到这两个问题:
1. 没有任何异常,view没能刷新。
2. android应用异常终止,打开logcat会看到这样的异常信息, Only the original thread that created a view hierarchy can touch its views。


最后,通过查文档,上网查询才知道,invalidate和postInvalidate方法需要使用android提供的handler,才能实现重绘 ,而在文档的说明中却只字不提,真是简单啊。具体是在需要重绘的地方调用handler的sendMessage方法发送消息,紧接着会os会触发 handler中的handlerMessage方法,在handlerMessage方法中再调用view的invalidate或者 postInvalidate方法就能实现重绘。


class CustomizeView extends WhichView {

public CustomizeView(Context context) {
super(context);
final Handler handler = new Handler();

new Thread(new Runnable() {
@Override
public void run() {
// delay some minutes you desire.
/*try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}*/
handler.post(new Runnable() {
public void run() {
concreteUpdateUI();
invalidate();
}
});
}
}).start();
}

protected void concreteUpdateUI() {
// Add concrete movement for UI updates.
// ...
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 贪吃蛇源码分析 下一篇关于Android如何获取屏幕分辨率的..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Announcing October (2025-12-24 15:18:16)
·MySQL有什么推荐的学 (2025-12-24 15:18:13)
·到底应该用MySQL还是 (2025-12-24 15:18:11)
·进入Linux世界大门的 (2025-12-24 14:51:47)
·Download Linux | Li (2025-12-24 14:51:44)