invalidate和postInvalidate的区别

至于什么invalidate,postInvalidate是做什么用的。
这个问题老外是这么回答的:
Each class which is derived from the View class has the invalidate and the postInvalidate method. If invalidate gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UIThread another method is needed for when you are not in the UIThread and still want to notify the system that your View has been changed. The postInvalidate method notifies the system from a non-UIThread and the View gets redrawn in the next eventloop on the UIThread as soon as possible. It is also briefly explained in the SDK documentation.
Just compare invalidate and postInvalidate.


只要是view的子类,都会从view中继承invalidate和postInvalidate这两个方法。
当invalidate方法被调用的时候,就是在告诉系统,当前的view发生改变,应该尽可能快的来进行重绘。
这个方法仅能在UI线程中被调用。如果想要在工作线程中进行刷新界面,那么其他的方法将会被调用,这个方法就是postInvalidate方法。
这个方法将会发送消息到主线程,当主线程的消息队列轮询到当前消息的时候,这个方法会被调用。


但是需要注意的是,刷新界面并不能保证马上刷新。只是尽可能快的进行刷新。尤其是在postInvalidate方法中,这种情况会出现。


至于可能会有人问postInvalidate是怎么保证线程安全的。那么我们需要看一下postInvalidate的源码:
public void postInvalidate() {
postInvalidateDelayed(0);
}


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
if (mAttachInfo != null) {
Message msg = Message.obtain();
msg.what = AttachInfo.INVALIDATE_MSG;
msg.obj = this;
mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
}


我们可以发现,其源码的原理依然是通过工作线程想主线程发送消息这一机制。
应该不难理解了吧。

猜你喜欢

转载自blog.csdn.net/xq_1358531/article/details/46999221