Android可实时更新的Toast工具类

Toast在连续调用时,会按照队列来一个一个的展示,体验很不好。我尝试了一种新的方式去展示一个Toast,达到实时更新Toast内容的目的,并且消失时间按最后一个Toast来计算倒计时。
因为使用了Activity的Context,所以用了弱引用来防止内存泄漏。查看SDK 27的Toast源码,使用Activity或Application的Context没有差别,Context只是用来获取PackageName和Resource。如果有误烦请指出,感谢!

public class ToastUtil {
	private static WeakReference<Toast> currentToast;
    private static WeakReference<Toast> nextToast;
    
    public static void show(Context context, @NonNull String text, int duration) {
       	Toast toast = Toast.makeText(context, text, duration);
        toast.getView().addOnAttachStateChangeListener(onAttachStateChangeListener);
        if (currentToast == null || currentToast.get() == null) {
            // 如果当前没有Toast,则直接显示
            show(toast);
        } else {
            // 如果当前存在Toast,先保存到下一个中,再取消当前这个
            nextToast = new WeakReference<>(toast);
            currentToast.get().cancel();
        }
    }

	private static void show(Toast toast) {
        toast.show();
        currentToast = new WeakReference<>(toast);
    }

	private final static View.OnAttachStateChangeListener onAttachStateChangeListener = new View.OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View v) {}

        @Override
        public void onViewDetachedFromWindow(View v) {
            if (currentToast != null) {
                currentToast.clear();
                currentToast = null;
            }
            if (nextToast != null && nextToast.get() != null) {
                // 存在下一个需要展示的,直接展示并替换到当前的引用中
                show(nextToast.get());
                nextToast.clear();
                nextToast = null;
            }
        }
    };
}

你可能感兴趣的:(Android)