Android 更新UI的两个方法

2014-11-24 03:11:47 · 作者: · 浏览: 3

在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"
/>