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

Android Toast 使用技巧

編輯:關於 Android 程式設計

問題

若短時間大量呼叫 Toast,可能造成提示不断堆疊。即使離開畫面,Toast 仍可能繼續顯示。

解法

可建立 ToastMaster,保存目前 Toast 實例。需要顯示新 Toast 前,先取消舊的。

public class ToastMaster {
    private static Toast sToast;

    public static void setToast(Toast toast) {
        if (sToast != null) {
            sToast.cancel();
        }
        sToast = toast;
    }

    public static void cancelToast() {
        if (sToast != null) {
            sToast.cancel();
            sToast = null;
        }
    }
}

使用方式

Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
ToastMaster.setToast(toast);
toast.show();

畫面離開時

可在 Activity 的 onDestroy 或頁面離開時呼叫 ToastMaster.cancelToast,避免提示殘留。

小結

透過集中管理 Toast,可避免大量提示互相覆蓋,也能讓使用者體驗更順暢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved