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

运行应用的时候出现了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();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值