【问题标题】:Android and toast duringAndroid 和 toast 期间
【发布时间】:2012-04-24 07:09:19
【问题描述】:

我在方法 showText();当我们调用该方法时,该方法会显示 toast。在第二个活动中,我有一个按钮,当我单击该按钮时,必须显示我的 Toast。一切都很好,但是当我点击两次或多次时,我的吐司会显示很长时间。我只想在单击按钮时显示吐司,当我再次单击时,第一个吐司消失并再次显示。

public void showText(String msg) {

        Toast.makeText(this, msg, 1000).show();

}

我该怎么做?

【问题讨论】:

    标签: android toast


    【解决方案1】:

    您可以保留对刚刚创建的 Toast 的引用,而不是调用 show()

    Toast toast = Toast.makeText(this, msg, 1000);
    then toast.show();
    and then later, call some methods on the toast like toast.cancel();
    

    http://developer.android.com/reference/android/widget/Toast.html

    【讨论】:

    • 当我在第一个活动中有这个 toast 和这个方法并且我想在第二个活动中使用那个解决方案时,这是有效的吗?
    • @edi233 应该这样做。但是 Toast.cancel() 在某些情况下似乎有问题,并且不会做任何事情。如果您无法使用 cancel() 您可能不得不求助于另一个解决方案(例如:您自己的自定义“toast”)。编辑:这不是回复您的评论的评论。
    【解决方案2】:

    你可以这样做

    class YourActivity extends Activity implements OnclickListener
    {
    
    Toast toast = null;
    
    void onclick(View v)
    {
    //call showText() method
    }
    
    // modify your showText as follows
    public void showText(String msg) {
    
      if(toast != null)
       {
        toast.cancel();
        toast = null;
       }
       toast = new Toast(YourActivity.this);
       toast.setText(msg);
       toast.show()
    
    }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-06
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 2013-07-15
      • 2013-04-08
      • 2014-01-08
      相关资源
      最近更新 更多