【问题标题】:Show Toast if there is no Toast already showing如果没有 Toast 已经显示,则显示 Toast
【发布时间】:2015-06-15 04:55:42
【问题描述】:

我有几个可以在片段上单击的按钮。单击每个按钮后,我会显示每个按钮完全相同的 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();
        }
    });
    }       
}

【问题讨论】:

  • 你的第二个代码在做什么?
  • 这就是我想要的。如果没有 toast 已经在运行,则显示 toast

标签: android runnable toast android-toast


【解决方案1】:

用途:

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

【讨论】:

  • 如何访问 toast 对象。它在一个单独的线程上运行。
  • 您可以将其存储在类成员变量中,即lastToast
  • 我编辑了我的答案。代码未经测试,但可能是一个开始。
【解决方案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

如果已经有 toast 则不等待,然后显示。但它确实会更改活动 toast 的文本并立即显示新的文本,而不会相互重叠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多