当我们在使用Toast的时候,发现如果有连续的10个Toast,需要show,我们就需要等待前9个都show()完成后,才能展示自己的,
这样肯定是不好的,我们应该做到当要展示第10个Toast的时候,直接展示,而不是等待,这样我们需要对Toast进行处理下,
我们使用下软引用。
public void show(Context context){ //如果当前的Toast正在被使用,就取消掉 if(mToast != null || mToast.get() != null){ mToast.get().cancel(); } Toast toast = Toast.makeText(context,"点击",Toast.LENGTH_LONG); toast.show(); mToa= new SoftReference<Toast>(toast); }
public class ToastUtil {
private static SoftReference<Toast> mToast;
public static final void show(Context context, @StringRes int resId){
show(context,getString(context,resId));
}
public static final void show(Context context,CharSequence message){
show(context,message,Toast.LENGTH_SHORT);
}
public static final void showLong(Context context,@StringRes int resId){
showLong(context,getString(context,resId));
}
public static final void showLong(Context context,CharSequence message){
show(context,message,Toast.LENGTH_LONG);
}
@Nullable
private static final String getString(Context context,@StringRes int resId){
if(context==null){
return null;
}
return context.getString(resId);
}
private static final void show(Context context,CharSequence message,int duration){
if(context ==null || TextUtils.isEmpty(message)){
return;
}
if(!ReferenceUtil.checkNull(mToast)){
mToast.get().cancel();
}
Toast toast = Toast.makeText(context,message,duration);
toast.show();
mToast = new SoftReference<>(toast);
}
}