Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> invalidate和postInvalidate的區別

invalidate和postInvalidate的區別

編輯:關於Android編程

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

應該不難理解了吧。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved