1. 程式人生 > >Android封裝吐司Toast

Android封裝吐司Toast

為了在今後的專案中避免toast寫多次,一下子出現多個toast的時候避免阻塞,這邊就乾脆將其封裝之後再用。


首先需要建立一個MyToast工具類:

public class MyToast {
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static Toast toast = null;
    private static Object synObj = new Object();
    public static void showMessage(final String msg) {
        showMessage(msg, Toast.LENGTH_SHORT);
    }
    /**
     * 根據設定的文字顯示
     * @param msg
     */
    public static void showMessage(final int msg) {
        showMessage(msg, Toast.LENGTH_SHORT);
    }
    /**
     * 顯示一個文字並且設定時長
     * @param msg
     * @param duration
     */
    public static void showMessage(final CharSequence msg, final int duration) {
        if (TextUtils.isEmpty(msg)) {
            MyLog.d("[ToastUtil] response message is null.");
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (synObj) { 
                   //加上同步是為了每個toast只要有機會顯示出來
                    if (toast != null) {
                        toast.setText(msg);
                        toast.setDuration(duration);
                    } else {
                        toast = Toast.makeText(BaseApplication.getInstance().getApplicationContext(), msg, duration);
                        TextView view = (TextView) toast.getView().findViewById(android.R.id.message);
                        if (view != null) {
                            view.setGravity(Gravity.CENTER);

                        }
                    }
                    toast.show();
                }
            }
        });
    }
    /**
     * 資原始檔方式顯示文字
     * @param id
     * @param duration
     */
    public static void showMessage(final int id, final int duration) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (synObj) {
                    if (toast != null) {
                        toast.setText(id);
                        toast.setDuration(duration);
                    } else {
                        toast = Toast.makeText(BaseApplication.getInstance().getApplicationContext(), id, duration);
                    }
                    toast.show();
                }
            }
        });
    }
}


將寫好的工具類應用在實際專案中:

MyToast.showMessage("我是吐司!");

學以致用,謝謝~