Android界面刷新的方法

灰太狼 2022-07-14 16:40 339阅读 0赞

Android界面刷新的方法

#

  1. Android 提供了 Invalidate 方法实现界面刷新,但是 Invalidate 不能直接在线程中调用,因为他是违背了单线程模型: Android UI 操作并不是线程安全的,并且这些操作必须在 UI 线程中调用。

Android 程序中可以使用的界面刷新方法有两种,分别是利用 Handler 和利用 postInvalidate() 来实现在线程中刷新界面。

利用 Handler 刷新界面

实例化一个 Handler 对象,并重写 handleMessage 方法调用 invalidate() 实现界面刷新;而在线程中通过 sendMessage 发送界面更新消息。

  1. // 在 onCreate() 中开启线程
  2. **new Thread(new GameThread()).start();**
  3. // 实例化一个 handler
  4. Handler myHandler = new Handler()
  5. \{
  6. // 接收到消息后处理
  7. public void handleMessage (Message msg)
  8. \{
  9. switch (msg.what)
  10. \{
  11. case Activity01.REFRESH:
  12. mGameView.**invalidate()** ; // 刷新界面
  13. break;
  14. \}
  15. super.handleMessage(msg);
  16. \}
  17. \};
  18. class GameThread implements Runnable
  19. \{
  20. public void run()
  21. \{
  22. while (!Thread.currentThread().isInterrupted())
  23. \{
  24. Message message = new Message();
  25. message.what = Activity01.REFRESH;
  26. // 发送消息
  27. Activity01.this.myHandler.**sendMessage** (message);
  28. try
  29. \{
  30. Thread.sleep(100);
  31. \}
  32. catch (InterruptedException e)
  33. \{
  34. Thread.currentThread().interrupt();
  35. \}
  36. \}
  37. \}
  38. \}

使用 postInvalidate() 刷新界面

使用 postInvalidate 则比较简单,不需要 handler ,直接在线程中调用 postInvalidate 即可

  1. class GameThread implements Runnable
  2. \{
  3. public void run()
  4. \{
  5. while (!Thread.currentThread().isInterrupted())
  6. \{
  7. try
  8. \{
  9. Thread.sleep(100);
  10. \}
  11. catch (InterruptedException e)
  12. \{
  13. Thread.currentThread().interrupt();
  14. \}
  15. // 使用 postInvalidate 可以直接在线程中更新界面
  16. mGameView.**postInvalidate** ();
  17. \}
  18. \}
  19. \}

参考:

Android 应用开发揭秘

Android 文档

http://www.cnblogs.com/feisky/archive/2010/08/24/1807433.html

发表评论

表情:
评论列表 (有 0 条评论,339人围观)

还没有评论,来说两句吧...

相关阅读