ToastUtils工具類

ToastUtils工具類
本來以爲這個工具類網上很好找,不過今天找了好久都不理想
所以自己就寫了個:

public class ToastUtils {

    protected static Toast toast = null;

    private static volatile ToastUtils mToastUtils;

    private ToastUtils(Context context) {
        toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
    }

    public static ToastUtils getInstance(Context context) {
        if (null == mToastUtils) {
            synchronized (ToastUtils.class) {
                if (null == mToastUtils) {
                    mToastUtils = new ToastUtils(context);
                }
            }
        }
        return mToastUtils;
    }

    public void showMessage(int toastMsg) {
        toast.setText(toastMsg);
        toast.show();
    }

    public void showMessage(String toastMsg) {
        toast.setText(toastMsg);
        toast.show();
    }

    public void toastCancel() {
        if (null != toast) {
            toast.cancel();
            toast = null;
        }
        mToastUtils = null;
    }

}

其中toastCancel()方法在Activity的onPause或者onstop或者onDestroy方法中調用都行,看個人喜好。

ToastUtils.getInstance(mContext).toastCancel();

其中mContext爲當前Activity的context。

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