ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
这两个 函数的作用都是重绘控件,区别在于: * Invalidate()函数一定要在主线程中执行,否则会报错; * postInvalidate()函数则没有那么多讲究,它可以在任何线程中执行,而不必一定是主线程。 在 postInvalidate()函数中就是利用 handler 给主线程发送刷新界面的消息来实现的,所以 它可以在任何线程中执行而不会出错。而正因为它是通过发送消息来实现的,所以它的界面刷新速度可能没有直接调用 Invalidate()函数那么快。 比如源码: ~~~ 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 final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); } } // mHandler final ViewRootHandler mHandler = new ViewRootHandler(); public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); mHandler.sendMessageDelayed(msg, delayMilliseconds); } ~~~ 对于处理消息,也就是直接使用View对象的invalidate()方法: ~~~ public void handleMessage(Message msg) { switch (msg.what) { case MSG_INVALIDATE: ((View) msg.obj).invalidate(); ... ~~~ 所以,在确定当前线程是主线程的情况下,还是以使用 Invalidate()函数为主;当不确定 当前要刷新界面的位置所处的线程是不是主线程的时候,还是使用 postInvalidate()函数为好,且postInvalidate()使用Hanlder来发送一个消息,最终还是使用invalidate()方法来进行刷新。