今天运行APP时突然闪退了,马上打开logcat看日志,看看什么情况,错误如下:
java.lang.RuntimeException: This Toast was not created with Toast.makeText()
显而易见,是自己的Toast出错了,这是为什么呢,终于在Toast.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 (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); }
就是还没在创建完成Toast时又调用了settext,所以出现了这个错误。。。。至于我为什么会出现,是因为自己没脑子。。。
修改代码如下:
public void showToast(String text) {
if (toast == null) {
toast = new Toast(mContext);
} else {
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(text);
}
toast.show();
}
仔细观察一下代码,问题显而易见,就是在第一次调用showToast时创建了Toast,但是还没创建完毕就又一个Toast事件出现,然后就报错了,所以写代码要认真啊。。。。