Toast 在安卓版本12上出现崩溃问题记录

在Android 12(API级别30)上,使用自定义View的Toast可能导致应用崩溃,错误信息提示需要去除之前的setView()调用。问题源于Android 30中Toast.setText()方法的改动,增加了对是否通过SystemUI显示的判断。解决方法是创建一个TextView直接设置文字,再将TextView传递给Toast,避免直接调用setText()。警告:变更targetSdkVersion可能导致类似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Toast 在安卓版本12上出现崩溃问题记录

Toast: 在日常开发中经常被使用。最近遇到一个问题 ToastUtil -- (我们自己封装的Toast)--在android - 29 及其以下手机版本时,能够正常使用,但是在android - 30 的手机上出现闪退 :

错误信息:

java.lang.IllegalStateException: Text provided for custom toast, remove previous setView() calls if you want a text toast instead.
        at android.widget.Toast.setText(Toast.java:540)

错误提示 Toast 的540行出问题了。 一直以来都是这样使用的,结果出现这个问题。

看源码:

  -----------------  在android - 30 上  setText 方法如下

/**
 * Update the text in a Toast that was previously created using one of the makeText() methods.
 * @param s The new text for the Toast.
 */
public void setText(CharSequence s) {
    if (Compatibility.isChangeEnabled(CHANGE_TEXT_TOASTS_IN_THE_SYSTEM)) {
        if (mNextView != null) {
            throw new IllegalStateException(
                    "Text provided for custom toast, remove previous setView() calls if you "
                            + "want a text toast instead.");
        }
        mText = s;
    } else {
        if (mNextView == null) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        TextView tv = mNextView.findViewById(com.android.internal.R.id.message);
        if (tv == null) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        tv.setText(s);
    }
}

  ------------------ 在android - 29 上代码如下 -------------

/**
 * Update the text in a Toast that was previously created using one of the makeText() methods.
 * @param s The new text for the Toast.
 */
public void setText(CharSequence s) {
    if (mNextView == null) {
        throw new RuntimeException("This Toast was not created with Toast.makeText()");
    }
    TextView tv = mNextView.findViewById(com.android.internal.R.id.message);
    if (tv == null) {
        throw new RuntimeException("This Toast was not created with Toast.makeText()");
    }
    tv.setText(s);
}

对比发现在 android -30 上多了  一个 关于 

Compatibility.isChangeEnabled(CHANGE_TEXT_TOASTS_IN_THE_SYSTEM)

的判断。判断toast 是否可以通过SystemUI来提供,而不是App。

解决办法:将View 改为TextView ,在创建TextView时 直接将文字设置到textView上,然后在将TextView 传递给Toast。

注意:  不能通过调整setText的顺序来修改问题,在android - 29上 优先调用setText 时  mNextView 为null ,依旧会出错。

警告: 没事不要随便变更 gradle 下 targetSdkVersion  的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值