This Toast was not created with Toast.makeText() 产生的原因和解决方法

Toast用于向用户显示一些提示,相信我们大家都用过,那么有些时候出于调用方便的原因,我们可能会封装成方法类。但是如果稍有不慎可能会产生一些问题。例如下面的代码:

private static Toast toast;

public static void showMsg(String msg) {
    Context context = BaseApplication.getAppContext();
    if (context == null|| TextUtils.isEmpty(msg)) {
        return;
    }
    if (toast == null) {
        toast = custom(context,msg,ContextCompat.getColor(context,R.color.toast_bg_color),
                ContextCompat.getColor(context,R.color.white),Toast.LENGTH_SHORT);
    } else {
        View view=toast.getView();
        TextView textView=view.findViewById(R.id.custom_toast_text);
        textView.setText(msg);
    }
    toast.show();
}



public static void showMsg(int msgResId) {
    Context context = BaseApplication.getAppContext();
    if (context == null) {
        return;
    }
    if (toast == null) {
        toast = Toast.makeText(context,
                msgResId,
                Toast.LENGTH_SHORT);
    } else {
        toast.setText(msgResId);
    }
    toast.show();
}

上边的代码我们判断了toast是否为null,达到了复用的效果。但是在调用了showMsg(String msg)方法后再调用showMsg(int msgResId)方法,可能会报出java.lang.RuntimeException: This Toast was not created with Toast.makeText()的异常。

主要原因:先执行 showMsg(String msg)方法之后,mToast.setView(view)把Toast中的contentView替换为自定义的view了。
而再执行showMsg(int msgResId)方法,toast对象不为空,复用了前面的对象。showMsg(int msgResId)中toast.setText(msgResId)这句代码是给指定的TextView设置msg文本,而这个指定的TextView是在默认的contentView中,这个时候contentView在 showMsg(String msg)方法中已经修改为自定义的view了,里面已经没有指定的那个TextView了。

解决方法:

1: showMsg(int msgResId)方法也同样修改成自定义的contentView。

2:分开维护两个toast对象。

这里推荐用第一种方法。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值