The best way to avoid toast accumulation in Android

In Android, when I create Toast and show them, they appear sequentially. The problem is that I have a button that checks some fields, and if the user enters incorrect data, a toast is displayed. If the user presses the button several times, the toasts accumulate and the message does not disappear for several seconds.

What is the best way to avoid this?

  • Is it possible to save the link to the last Toast and delete it before making a new one?
  • Should I use the same Toast for all posts?
  • Can I use any method that cleans all Toasts applications before creating and displaying a new one?
+6
source share
2 answers

You can use the cancel() method of Toast to close the Toast display.

Use a variable to keep a link to each Toast while you show it, and just call cancel() before showing the other.

 private Toast mToast = null; // <-- keep this in your Activity or even in a custom Application class //... show one Toast if (mToast != null) mToast.cancel(); mToast = Toast.makeText(context, text, duration); mToast.show(); //... show another Toast if (mToast != null) mToast.cancel(); mToast = Toast.makeText(context, text, duration); mToast.show(); // and so on. 

You can even wrap this in a small class:

 public class SingleToast { private static Toast mToast; public static void show(Context context, String text, int duration) { if (mToast != null) mToast.cancel(); mToast = Toast.makeText(context, text, duration); mToast.show(); } } 

and use it in your code as follows:

 SingleToast.show(this, "Hello World", Toast.LENGTH_LONG); 

//

+26
source

There is only one toast in this exercise.

 private Toast toast = null; 

Then just check if Toast currently displayed before creating another.

 if (toast == null || !toast.getView().isShown()) { if (toast != null) { toast.cancel(); } toast = Toast.makeToast("Your text", Toast.LENGTH).show(); } 

You can even make this last snippet into the private showToast(text) method for refactoring code if you need to display various text messages.

+1
source

Source: https://habr.com/ru/post/953394/