Android常用工具類之 Toast工具類

編寫Toast工具類的必要性

Toast作爲Android的一種用戶提醒方式被廣泛應用在Android應用中,但是Toast的使用卻有些問題:
1. 調用代碼繁瑣:
首先需要調用靜態方法makeText(Context context, CharSequence text, @Duration int duration)來創建一個Toast對象。
其次還要記得調用show函數來彈出該toast
2. 多次調用延遲
當多次連續彈出toast時,會導致排在後面的toast會延遲許久才顯示,也許用戶早已經離開情景界面,用戶體驗不好
3. 不能非UI線程調用
Toast的彈出值能在UI線程調用,如果後臺調用顯示,就會觸發RuntimeException。導致FC。

解決以上三個問題:

  1. 通過工具類的靜態方法就可以直接顯示Toast。
  2. 如果當前有Toast顯示,則讓當前toast消失,顯示正在調用的toast
  3. 通過建立一個UI線程的Looper綁定的Handler,講Toast的顯示通過該handler來post運行。

完整代碼:


package com.example.pc.myapplication;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

public class ToastUtils {

    private static Handler sMainThreadHandler;
    private static Toast mToast;

    public static Handler getMainThreadHandler() {
        if (sMainThreadHandler == null) {
            synchronized (ToastUtils.class){
                if(sMainThreadHandler==null){
                    sMainThreadHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        return sMainThreadHandler;
    }


    public static void showToast(final Context context, final String message, final int duration) {
        if (mToast != null) {
            mToast.cancel();
        }

        getMainThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                mToast = Toast.makeText(context.getApplicationContext(), message, duration);
                mToast.show();
            }
        });
    }

    public static void showToastLong(final Context context, final String message) {
        showToast(context, message, Toast.LENGTH_LONG);
    }

    public static void showToastShort(final Context context, final String message) {
        showToast(context, message, Toast.LENGTH_SHORT);
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章