您的位置:首页 > 产品设计 > UI/UE

Android更新UI的两种方法

2015-11-12 00:13 423 查看
在Android中,只有UI线程(主线程)可以对UI进行更新操作,其他线程对UI操作会导致android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views。

第一种:在Activity线程中创建Handler实例,通过Handler的handleMessage(Message)方法,接受其他线程的消息,进行UI更新。

其他线程通过Handler的sendMessage(Message)方法,把更新消息发送到UI线程的Handler,通知UI更新。

第二种:利用Activity.runOnUiThread(Runnable)把更新UI的代码创建在Runnable中,然后在需要更新UI时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。

 这样Runnable对像就能在UI程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI 线程。

runOnUiThread的实现代码:

public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
   mHandler.post(action);
} else {
   action.run();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息