Toast的优化操作

当我们在使用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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值