设为首页 加入收藏

TOP

Android 更新UI的两个方法
2014-11-24 03:11:47 来源: 作者: 【 】 浏览:2
Tags:Android 更新 两个 方法

在Android的开发过程中,常常需要适时的更新UI。Androd中的UI是在主线程中更新的。如果在主线程之外的线程中直接更新,就会出现报错并抛出异常:


android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.


只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)


那么Android中该如何更新UI呢?


<1>. 利用Activity.runOnUiThread(Runnable)把更新UI的代码写在Runnable中


操作机制:如果当前线程是UI线程,那么该行动立即执行;如果不是,操作发布到事件队列的UI线程。


RunOnUiThreadDemo


布局文件:activity_mai.xml


xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
/>

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android Handler消息传递机制 下一篇Linux下编译运行驱动

评论

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

·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)
·索引堆及其优化 - 菜 (2025-12-24 20:18:50)
·Shell 中各种括号的 (2025-12-24 19:50:39)
·Shell 变量 - 菜鸟教 (2025-12-24 19:50:37)