invalidate()与postInvalidate()这两个都是刷新View的API,它们主要的区别是invalidate()可以在主线程(UI线程)中调用,而不能在子线程中调用,若在子线程中进行刷新view的操作需要配合handler来使用。而postInvalidate()可以在子线程中直接调用。
我们知道AndroidUI操作不是线程安全的,所有更新UI的操作必须放到主线程中来进行,postInvalidate()为何却可以在子线程中直接调用?
翻开View.java的postInvalidate()发现如下代码:
public void postInvalidate() {
postInvalidateDelayed(0);
}
而postInvalidateDelayed()又做了哪些操作?
public void postInvalidateDelayed(long delayMilliseconds) {
// We try only with the AttachInfo because there's no point in invalidating
// if we are not attached to our window
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
}
}
public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INVALIDATE:
((View) msg.obj).invalidate();
break;
发现postInvalidate()底层也是通过handler来调用View的Invalidate()来刷新UI的,整个过程清晰明了了。