开发者

How to immediately replace the current toast with a second one without waiting for the current one to finish? [duplicate]

开发者 https://www.devze.com 2023-03-16 04:17 出处:网络
This question already has answers here: How to prevent Multiple Toast Overlaps (9 answers) Closed 7 years ago.
This question already has answers here: How to prevent Multiple Toast Overlaps (9 answers) Closed 7 years ago.

I have many buttons. And on click of each of them I show a Toast. But while a toast loads and show in view, another button is clicked and the toast is not displayed until the one that is being displayed finishes.

So, I would like to sort out a way to detect if a toast is showing in the current context. Is there a way to know if a t开发者_StackOverflow社区oast is being displayed such that I can cancel it and display a new one.


You can cache current Toast in Activity's variable, and then cancel it just before showing next toast. Here is an example:

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

}

Another way to instantly update Toast message:

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

精彩评论

暂无评论...
验证码 换一张
取 消