11

My application displays a Toast when a certain action happens. If two of these actions happen in close proximity, however, I would like to forgo displaying the first Toast, instead displaying only the second one. I thought Toast.cancel() would do the trick, but what it does is simply hide the first toast; the second one only displays after the first one would have finished displaying anyway.

Example code:

Toast toast1 = Toast.makeText(parentActivity, "Test1", Toast.LENGTH_SHORT);
Toast toast2 = Toast.makeText(parentActivity, "Test2", Toast.LENGTH_SHORT);

toast1.show();
toast2.show();

toast1.cancel();

The second Toast shows up only after waiting a short while (the length of the short duration). This in fact happens even if I call toast2.cancel().

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Joey Marianer
  • 728
  • 1
  • 5
  • 18
  • 1
    I have had good results from [my `Boast.java` class referenced in this related post](http://stackoverflow.com/questions/16098151/android-cancel-toast-when-exiting-the-app-and-when-toast-is-being-shown). I've not had a problem with `.cancel()` not working properly. – Richard Le Mesurier Aug 16 '16 at 21:16

2 Answers2

1

Toast.makeText(context, text, duration) returns a Toast object. Call cancel() method on this object to cancel it.

Example:

Toast mToastText = Toast.makeText(getApplicationContext(), "Hello StackOverFlow!", Toast.LENGTH_SHORT);
 mToastText.cancel();
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
1

I'm not sure this would work, but maybe try cancelling both of them and then showing the second one again.

Liquid_Fire
  • 6,990
  • 2
  • 25
  • 22
  • 3
    Sorry, same result: Test2 appears but is delayed. I actually found that in the Toast source code, the only thing "cancel" does is hides the view, not dequeue the toast in the system. – Joey Marianer Feb 03 '11 at 16:57