如果已经显示了一个Toast,如何避免Toast

Dee*_*oel 37 android android-toast

我有几个SeekBaronSeekBarProgressStop()我想显示Toast的消息.

但是,如果在SeekBar我快速执行操作,那么UI线程以某种方式阻止和Toast消息等待直到UI线程是空闲的.

现在我的担心是Toast如果Toast消息已经显示,则避免新消息.或者是我们检查UI线程当前是否空闲的任何条件,然后我将显示该Toast消息.

我通过使用runOnUIThread()和创建新的两种方式尝试了它Handler.

Add*_*ddi 58

我已经尝试过各种各样的事情来做这件事.起初我尝试使用cancel(),对我没有任何影响(另见这个答案).

随着setDuration(n)我不是来无论在任何地方.通过记录它结果getDuration()表明它携带值0(如果makeText()参数是Toast.LENGTH_SHORT)或1(如果makeText()参数是Toast.LENGTH_LONG).

最后我试着检查吐司的观点isShown().当然,如果没有显示吐司,则不是这样,但更重要的是,在这种情况下它会返回致命错误.所以我需要尝试捕捉错误.现在,isShown()如果显示toast ,则返回true.利用isShown()我想出的方法:

    /**
     * <strong>public void showAToast (String st)</strong></br>
     * this little method displays a toast on the screen.</br>
     * it checks if a toast is currently visible</br>
     * if so </br>
     * ... it "sets" the new text</br>
     * else</br>
     * ... it "makes" the new text</br>
     * and "shows" either or  
     * @param st the string to be toasted
     */

    public void showAToast (String st){ //"Toast toast" is declared in the class
        try{ toast.getView().isShown();     // true if visible
            toast.setText(st);
        } catch (Exception e) {         // invisible if exception
            toast = Toast.makeText(theContext, st, toastDuration);
            }
        toast.show();  //finally display it
    }
Run Code Online (Sandbox Code Playgroud)

  • 好答案.一句话:原因isShown()"引发异常"是toast.getView()最初返回null.简单地测试null而不是使用try ... catch. (15认同)
  • 只需测试null - 很酷!谢谢@Paul-Jan (2认同)

J W*_*ang 37

以下是最流行答案的替代解决方案,没有try/catch.

public void showAToast (String message){
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        mToast.show();
}
Run Code Online (Sandbox Code Playgroud)