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 的值。