Search code examples
androidandroid-layout

How can I immediately replace the current toast with a second one without waiting for the current one to finish?


I have many buttons. And on click of each of them I show a Toast. But while a toast loads and shows in the 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 toast is being displayed such that I can cancel it and display a new one?


Solution

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