How to avoid a Toast if there's one Toast already being shown
I've tried a variety of things to do this. At first I tried using the cancel()
, which had no effect for me (see also this answer).
With setDuration(n)
I wasn't coming to anywhere either. It turned out by logging getDuration()
that it carries a value of 0 (if makeText()
's parameter was Toast.LENGTH_SHORT
) or 1 (if makeText()
's parameter was Toast.LENGTH_LONG
).
Finally I tried to check if the toast's view isShown()
. Of course it isn't if no toast is shown, but even more, it returns a fatal error in this case. So I needed to try and catch the error.
Now, isShown()
returns true if a toast is displayed.
Utilizing isShown()
I came up with the method:
/**
* <strong>public void showAToast (String st)</strong></br>
* this little method displays a toast on the screen.</br>
* it checks if a toast is currently visible</br>
* if so </br>
* ... it "sets" the new text</br>
* else</br>
* ... it "makes" the new text</br>
* and "shows" either or
* @param st the string to be toasted
*/
public void showAToast (String st){ //"Toast toast" is declared in the class
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
}
The following is an alternative solution to the most popular answer, without the try/catch.
public void showAToast (String message){
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
mToast.show();
}
A clean solution that works out of the box. Define this on your Activity:
private Toast toast;
/**
* Use this to prevent multiple Toasts from spamming the UI for a long time.
*/
public void showToast(CharSequence text, int duration)
{
if (toast == null)
toast = Toast.makeText(this, text, duration);
else
toast.setText(text);
toast.show();
}
public void showToast(int resId, int duration)
{
showToast(getResources().getText(resId), duration);
}