歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中用Toast.cancel()方法優化toast內容的顯示

Android中用Toast.cancel()方法優化toast內容的顯示

日期:2017/3/1 10:38:41   编辑:Linux編程

產品在測試過程中發現一個bug,就是測試人員不停的瘋狂的點擊某個按鈕,觸發了toast以後,toast內容會一直排著隊的顯示出來,不能很快的消失。這樣可能會影響用戶的使用。

看到Toast有一個cancel()方法:

void cancel() Close the view if it's showing, or don't show it if it isn't showing yet.做程序員的,基本一看api就知道,用這個可以取消上一個toast的顯示,然後顯示下一個,這樣就能解決出現的問題。可是在測試的過程中,發現卻沒有想象中的那麼簡單,不信可以百度一下,很多很多人發現toast的cancel()方法不起作用。還是不講具體過程,只講結果吧。

我把toast做成了一個應用類,方便使用,大家可以直接用:

  1. package com.arui.framework.Android.util;
  2. import android.content.Context;
  3. import android.os.Handler;
  4. import android.os.Looper;
  5. import android.widget.Toast;

  1. /**
  2. * Toast util class.
  3. *
  4. * @author <a href="http://www.linuxidc.com">http://www.linuxidc.com</a>
  5. * @version 2011/11/30
  6. *
  7. */
  8. public class ToastUtil {
  9. private static Handler handler = new Handler(Looper.getMainLooper());
  10. private static Toast toast = null;
  11. private static Object synObj = new Object();
  12. public static void showMessage(final Context act, final String msg) {
  13. showMessage(act, msg, Toast.LENGTH_SHORT);
  14. }
  15. public static void showMessage(final Context act, final int msg) {
  16. showMessage(act, msg, Toast.LENGTH_SHORT);
  17. }
  18. public static void showMessage(final Context act, final String msg,
  19. final int len) {
  20. new Thread(new Runnable() {
  21. public void run() {
  22. handler.post(new Runnable() {
  23. @Override
  24. public void run() {
  25. synchronized (synObj) {
  26. if (toast != null) {
  27. toast.cancel();
  28. toast.setText(msg);
  29. toast.setDuration(len);
  30. } else {
  31. toast = Toast.makeText(act, msg, len);
  32. }
  33. toast.show();
  34. }
  35. }
  36. });
  37. }
  38. }).start();
  39. }
  40. public static void showMessage(final Context act, final int msg,
  41. final int len) {
  42. new Thread(new Runnable() {
  43. public void run() {
  44. handler.post(new Runnable() {
  45. @Override
  46. public void run() {
  47. synchronized (synObj) {
  48. if (toast != null) {
  49. toast.cancel();
  50. toast.setText(msg);
  51. toast.setDuration(len);
  52. } else {
  53. toast = Toast.makeText(act, msg, len);
  54. }
  55. toast.show();
  56. }
  57. }
  58. });
  59. }
  60. }).start();
  61. }
  62. }

代碼的邏輯很簡單。這裡加了同步,這樣做可以確保每一個toast的內容至少可以顯示出來,而不是還沒顯示就取消掉了。這樣做,是因為toast的內容不一定完全相同,如果沒顯示出來,也會有問題。

Copyright © Linux教程網 All Rights Reserved