Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

invalidate 與 postInvalidate 到底有什麼不同

編輯:關於 Android 程式設計

談到 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.

簡單歸納這段話:只要是 View 的子類,都會從 View 繼承到 invalidate 與 postInvalidate 這兩個方法。

  • invalidate:呼叫時是在告訴系統「目前的 View 已改變,請盡快重繪」。但這個方法只能在 UI 執行緒中被呼叫。
  • postInvalidate:如果你需要在工作執行緒(非 UI 執行緒)中刷新介面,就必須改用這個方法。它會發送訊息到主執行緒,當主執行緒的訊息佇列輪詢到該訊息時便會被處理。

需要留意的是,呼叫這兩個方法並不代表介面會「立刻」刷新,而只是「盡可能快」地安排重繪,使用 postInvalidate 時尤其如此。

postInvalidate 如何保證執行緒安全

那麼 postInvalidate 是怎麼做到執行緒安全的呢?我們來看它的原始碼:

public void postInvalidate() {
    postInvalidateDelayed(0);
}

public void postInvalidateDelayed(long delayMilliseconds) {
    // 只有在已附加到視窗時才有重繪的意義
    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