invalidate和postInvalidate的區別

至於什麼invalidate,invalidate是做什麼用的。

這個問題老外是這麼回答的:

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的源碼:

 

[html] 
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); 
        } 
    } 

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);
        }
    }
我們可以發現,其源碼的原理依然是通過工作線程想主線程發送消息這一機制。

應該不難理解瞭吧。

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *