本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”关注,和我一起每天进步一点点
我们在自定义View时免不了要使用invalidate方法,这个方法的作用大家也比较清楚,就是让我们的View进行刷新重新绘制的。但是postInvalidate方法可能就不是那么熟悉了,因为平时开发时invalidate方法相对而言会用得比较多。不过需要大家注意的是,面试官在问到View相关的问题时,就很有可能会问到postInvalidate方法,所以我们还是有必要来学习一下。
那invalidate方法和postInvalidate方法到底有什么区别呢?
invalidate方法和postInvalidate方法的区别
其实答案也很简单,就一句话:
invalidate方法和postInvalidate方法都是用于进行View的刷新,invalidate方法应用在UI线程中,而postInvalidate方法应用在非UI线程中,用于将线程切换到UI线程,postInvalidate方法最后调用的也是invalidate方法。
当然,空口无凭,我们还是来看看源码
invalidate方法和postInvalidate方法源码分析
我们先来看看View中的postInvalidate方法
@UiThread
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {
...
public void postInvalidate() {
postInvalidateDelayed(0);
}
public void postInvalidate(int left, int top, int right, int bottom) {
postInvalidateDelayed(0, left, top, right, bottom);
}
public void postInvalidateDelayed(long delayMilliseconds) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
}
}
...
}
从源码中我们可以看到,postInvalidate方法最后调用了ViewRootImpl的dispatchInvalidateDelayed方法
//ViewRootImpl.class
final ViewRootHandler mHandler = new ViewRootHandler();
public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
ViewRootImpl中的dispatchInvalidateDelayed方法就是像ViewRootHandler发送了一个MSG_INVALIDATE消息,ViewRootHandler是ViewRootImpl中的一个内部Handler类
final class ViewRootHandler extends Handler {
@Override
public String getMessageName(Message message) {
switch (message.what) {
case MSG_INVALIDATE:
return "MSG_INVALIDATE";
...
}
return super.getMessageName(message);
}
...
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INVALIDATE:
((View) msg.obj).invalidate

最低0.47元/天 解锁文章
842

被折叠的 条评论
为什么被折叠?



