论坛首页 移动开发技术论坛

Toast使用注意--解决错误:The application ** has stopped unexpectedly.Please try again

浏览 3470 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-09-17  

运行应用的时候出现了The application ** has stopped unexpectedly.Please  try again 的错误,如下图:

 

通过debug发现异常信息为:

Caused by: java.lang.RuntimeException: This Toast was not created with Toast.makeText()

    at android.widget.Toast.setText(Toast.java:275)

    at cn.and.ToastActivity.onCreate(ToastActivity.java:20)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

 

分析andriod源码发现:

public void setText(CharSequence s) {  
        if (mNextView == null) {  
            throw new RuntimeException("This Toast was not created with Toast.makeText()");  
        }  
        TextView tv = (TextView) 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);  
}
如果不指定view,则mNextView的值为null。就会抛出异常。另外使用第一种方式时,就算你为Toast设置好了View也不能这样调用:toast.setText(s);

会抛出This Toast was not created with Toast.makeText()异常。解决的办法是定义一个TextView,然后为TextView赋值,再加到XXLayout中,

使用setView(XXLayout)把XXLayout设置成Toast的View。

 

弹出提示的代码修改如下:

	/**
	 * 显示Toast
	 * @param toastTxt 提示文本内容
	 */
	private void showToast(String toastTxt) {
		Toast t = new Toast(this);
		t.setDuration(Toast.LENGTH_SHORT);
		LinearLayout layout = new LinearLayout(this);
		TextView textView = new TextView(this);
		textView.setText(toastTxt);
//		textView.setTextSize(16);
		layout.addView(textView);
		t.setView(layout);
		t.show();
	}
 
论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics