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。

你可能感兴趣的:(android)