Android界面刷新


  Android的invalidate與postInvalidate都是用來刷新界面的,用法區別在於:

  1)invalidate():實例化一個Handler對象,並重寫handleMessage方法調用invalidate()實現界面刷新;而在線程中通過sendMessage發送界面更新消息。 

// 在onCreate()中開啟線程
new Thread(new GameThread()).start();

// 實例化一個handler
Handler myHandler = new Handler() {
  // 接收到消息后處理
  public void handleMessage(Message msg) {
    switch (msg.what) {
      case Activity01.REFRESH:
        mGameView.invalidate(); // 刷新界面
        break;
    }

    super.handleMessage(msg);
  }
};

class GameThread implements Runnable {
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      Message message = new Message();
      message.what = Activity01.REFRESH;
      // 發送消息
      Activity01.this.myHandler.sendMessage(message);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
  }
}

  2)使用postInvalidate則比較簡單,不需要handler,直接在線程中調用postInvalidate即可

class GameThread implements Runnable {
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }

      // 使用postInvalidate可以直接在線程中更新界面
      mGameView.postInvalidate();
    }
  }
}

 

 --------------------------------------------------------------------

PS: 歡迎關注公眾號"Devin說",會不定期更新Java相關技術知識。

--------------------------------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM