Android 更新UI的两种方法
2018-11-04 本文已影响0人
沈默的头号狗腿
在Android开发过程中,常需要更新界面的UI。而更新UI是要主线程来更新的,即UI线程更新。如果在主线线程之外的线程中直接更新页面显示常会报错。只有原始创建这个视图层次的线程才能修改它的视图。
那么如果需要在主线程之外的线程中更新页面,android为我们提供了两种方法,handler和runOnUiThread()
runOnUiThread()
runOnUiThread()是activity中的方法
例


上述例子就是一个okhttp异步回调函数中调用runOnUiThread()更改UI。
handler
例

可以看到,通过在子线程中调用自定义的handle的handleMessage方法可实现UI的更新
至于这两种方式是如何实现子线程中更新UI的,后面再作更新。