如何立即用第二个 Toast 替换当前的 Toast,而不等待当前的 Toast 完成? [重复]

问题描述 投票:0回答:1

我有很多按钮。单击每个按钮时,我会显示一个 Toast。但是,当 Toast 加载并显示在视图中时,单击另一个按钮,直到正在显示的 Toast 完成后才会显示 Toast。

所以,我想找出一种方法来检测当前上下文中是否显示吐司。有没有办法知道是否正在显示吐司,以便我可以取消它并显示新的吐司。

android android-layout
1个回答
34
投票

您可以将当前的

Toast
缓存在 Activity 的变量中,然后在显示下一个 toast 之前取消它。这是一个例子:

Toast m_currentToast;

void showToast(String text)
{
    if(m_currentToast != null)
    {
        m_currentToast.cancel();
    }
    m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    m_currentToast.show();

}

即时更新

Toast
消息的另一种方式:

void showToast(String text)
{
    if(m_currentToast == null)
    {   
        m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    }

    m_currentToast.setText(text);
    m_currentToast.setDuration(Toast.LENGTH_LONG);
    m_currentToast.show();
}
© www.soinside.com 2019 - 2024. All rights reserved.