设为首页 加入收藏

TOP

Android 更新UI的两个方法
2014-11-24 03:11:47 来源: 作者: 【 】 浏览:1
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下编译运行驱动

评论

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

·C++ 语言社区-CSDN社 (2025-12-24 17:48:24)
·CSDN问答专区社区-CS (2025-12-24 17:48:22)
·C++中`a = b = c`与` (2025-12-24 17:48:19)
·C语言结构体怎么直接 (2025-12-24 17:19:44)
·为什么指针作为c语言 (2025-12-24 17:19:41)