ToastMgr

Android原生的Toast虽说不复杂, 但也不是很方便, 如果需要更换Toast的背景, 则需要写不少重复代码. 本着遵循DRY的原则, 理当将Toast封装一下:

public class ToastMgr {
    private static Toast it;

    private ToastMgr() {
    }

    /**
     * 在程序初始化的时候调用, 只需调用一次
     */
    public static void init(Context _context) {
        View v = Toast.makeText(_context, "", Toast.LENGTH_SHORT).getView();
        init(_context, v);
    }

    /**
     * 在程序初始化的时候调用, 只需调用一次
     */
    public static void init(Context _context, View view) {
        it = new Toast(_context);
        it.setView(view);
    }

    /**
     * 设置Toast背景
     */
    public static void setBackgroundView(View view) {
        checkInit();
        it.setView(view);
    }

    public static void show(CharSequence text, int duration) {
        checkInit();
        it.setText(text);
        it.setDuration(duration);
        it.show();
    }

    public static void show(int resid, int duration) {
        checkInit();
        it.setText(resid);
        it.setDuration(duration);
        it.show();
    }

    public static void show(CharSequence text) {
        show(text, Toast.LENGTH_SHORT);
    }

    public static void show(int resId) {
        show(resId, Toast.LENGTH_SHORT);
    }

    private static void checkInit() {
        if (it == null) {
            throw new IllegalStateException("ToastMgr is not initialized, please call init once before you call this method");
        }
    }
}

ToastMgr持有一个Toast的单例, 并且通过Toast.makeText(_context, "", Toast.LENGTH_SHORT).getView()来获取系统默认的吐司背景. 也可通过setBackgroundView(View view)来给Toast设置自定义的背景. 默认情况下只需通过以下方式调用:

ToastMgr.show("toast");

但是需要在程序初始化的时候调用如下方法, 建议使用ApplicationContext:

ToastMgr.init(getApplicationContext());

通过ToastMgr产生的Toast与系统自带的Toast有一个最大的区别就是, 不论前面有多少Toast, 都会被最后一个Toast覆盖, 然后2秒后消失. 原生自带的则是一个接一个的显示. 因为ToastMgr中的是Toast单例, 而原生的不是.

Last updated