如果没有Toast已经显示,则显示Toast

时间:2015-04-09 17:24:04

标签: android runnable toast android-toast

我有几个可以点击片段的按钮。单击每个按钮后,我会显示每个按钮完全相同的Toast消息。因此,如果您一个接一个地按下5个不同的按钮,您将叠加5个Toast消息,这将最终显示相同的消息很长一段时间。我想要做的是在没有Toast当前正在运行的情况下显示Toast。

我用来显示Toast消息的方法

public void showToastFromBackground(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

按下按钮时,我只需拨打showToastFromBackground("Text to show");

我真正想要的是像

public void showToastFromBackground(final String message) {
    if(toastIsNotAlreadyRunning)
    {
        runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        }
    });
    }       
}

2 个答案:

答案 0 :(得分:2)

试试isShown()。如果toast不是shown,则会返回致命错误。因此,您可以使用try and catch错误。

//"Toast toast" is declared in the class

 public void showAToast (String st){ 
        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
 }

来自here

如果已经有吐司,则不等待,然后显示。但它确实改变了活动的吐司的文本并立即显示新的文本而没有相互重叠的祝酒词。

答案 1 :(得分:2)

使用:

toast.getView().isShown();

或者:

if (toast == null || toast.getView().getWindowVisibility() != View.VISIBLE) {
    // Show a new toast...
}

编辑:

Toast lastToast = null; // Class member variable

public void showToastFromBackground(final String message) {
    if(isToastNotRunning()) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                lastToast = Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG);
                lastToast.show();
            }
        });
    }       
}

boolean isToastNotRunning() {
    return (lastToast == null || lastToast.getView().getWindowVisibility() != View.VISIBLE);
}
相关问题