12

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 toast is being displayed such that I can cancel it and display a new one.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • I think you are better off using the notifications framework to display your messages as you would be displaying multiple messages at the same time. If you use the toast or alert box solution you would need to manage positions/multiple pop ups , Notifications should help in simplifying your program. – Ravi Vyas Jun 27 '11 at 18:21

1 Answers1

34

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();
}
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • 2
    What about showing multiple toasts at the same time. Creating multiple instances and showing at distinct places in the view window ! Is this how it can be done ? – Sandeep Jun 27 '11 at 17:51
  • I think a popup might work better for you in this situation. Much more flexible with things like that. – DustinRiley Jun 27 '11 at 17:54
  • I was looking for a way to cancel the existing toast if I show a new one. Your first example doesn't work well for me, but the second version works great for my needs! – bmaupin Mar 01 '12 at 18:54
  • 1
    I suggest you put the setText(text) of your second answer in else block, so that the text is not set 2 times for newly created toast. – Barun Oct 31 '14 at 15:42
  • this is awesome! Thank you! if you combine it with a Singelton, you can use one toast overall the app and never get sick of still showing toasts! – Visores Jul 15 '15 at 08:10