背景:
在开发过程中会经常使用到Toast,对用户进行一定程度的提醒和引导,但由于一些原因导致Toast重复触发,会造成相同的提示一直重复显示的情况,为此,我们可以自己写一个Toast,避免重复显示的尴尬。
实现:
public class ToastUtil {
private static Toast mToast = null;
private static String mLastText = "";
private static long mLastTime = 0;
private static long mLastDuration = 0;
public static void showToast(String text, int duration) {
if (mToast == null) {
mToast = Toast.makeText(Utils.getApp(), text, duration);
} else {
if (Objects.equals(text, mLastText) && System.currentTimeMillis() - mLastTime < mLastDuration) {
return;
}
mToast.cancel();
mToast = Toast.makeText(Utils.getApp(), text, Toast.LENGTH_SHORT);
mLastDuration = duration;
mLastTime = System.currentTimeMillis();
mLastText = text;
}
mToast.show();
}
}
其中Utils.getApp()为全局的ApplicationContext,之后只需在用到的地方调用即可。
ToastUtil.showToast("Test", 2000);