This Toast was not created with Toast.makeText()的解决办法

最近写程序想要自定义一下吐司的布局,这可难为坏我了,先上代码:
项目部分代码

运行以后结果一直报This Toast was not created with Toast.makeText(),这就话的错误,楼主不服,各种谷歌,百度,各种偏方都试过了,但是还是解决不了,于是只能去看源码了:
Toast源码

这里写图片描述

报了上面的错,原来是因为tv为null,看到这里也许你就明白了,就是Toast的setText的方法设置的是系统自带布局里面的TextView上的文字,系统布局只有在makeText的时候才会被调用,上面我使用的时候,调用了new Toast()这个方法去初始化了一个Toast,并没有加载这个默认的布局,所以我在调用了toast.setView()以后,在设置setText肯定就报错了.

怎么解决呢?很简单,直接在布局上面放一个TextView就行了.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:background="@drawable/circular_black_bg"
            android:layout_width="@dimen/dp_100"
            android:layout_height="@dimen/dp_100" />

        <TextView
            android:id="@+id/toastText"
            android:textSize="30sp"
            android:layout_centerInParent="true"
            android:text="L"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</RelativeLayout>

xml预览图

在代码中不要写toast.setText(),这么写:

                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = new Toast(mContext);
                View toastView = View.inflate(mContext, R.layout.toast_view_layout, null);
                mToast.setGravity(Gravity.CENTER, 0, 0);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setView(toastView);
                TextView tv_toast = (TextView) mToast.getView().findViewById(R.id.toastText);
                tv_toast.setText(word);
                mToast.show();

这样就可以这正常的运行了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值