`

android Toast

阅读更多

最近在做一个android项目,测试人员通过不对点击按钮,呈现出Toast,当用户退回到上一个页面时,Toast的提示信息

 

还是没有消失。

 

关于这个问题,起初我认为可以通过设置Toast的显示的时间来解决该问题,Toast.LENGTH_LONG表示的为常时间显示,

 

而Toast.LENGTH_SHORT设置的时间为短时间显示,但是情况还是没解决。

 

以前为传统的Toast.makeText(this, "aa", Toast.LENGTH_SHORT);方式显示,后来修改了Toast的现实方式为如下

 

   private void shwoToast(Context context, int resouce, int duration)
    {
        Toast toast = new Toast(this);
        toast.setDuration(duration);

        toast.setText(context.getString(resouce));
        toast.show();
    }

 

结果不但问题没解决,程序却出现了如下错误

 

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)

 

通过查询相关的源码,具体源码如下:

  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);
    }

 

如果采用上述我方式,没有设置TextView,则程序就会出现以上的错误。解决的办法是使用Toast.makeText方法创建

 

Toast即可。

 

最后通过查询相关资料,终于找到了解决办法,具体如下:

  protected void showToast(Context context, String string, int length)
    {

       //声明Toast
        Toast showToast = Toast.makeText(this, "toast text", Toast.LENGTH_SHORT);
        showToast.setText(string);
        showToast.setDuration(length);
        showToast.show();
    }

 

一定要申明Toast,在去设置Toast的相关属性值,这样才能解决多次点击Toast,返回到上一页面Toast提示信息不消失

 

的问题

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics