In Android, when I create Toast and show them, they appear consecutively. The problem is that I have a button that checks some fields and if the user enters incorrect data, a Toast is shown. If the user touches the button repeatedly, Toasts are accumulated and the message does not disappear for a couple of seconds.
Which is the best way to avoid that?
"Settings" > "Notifications" > under "Recently Sent", click "More" > then at the top, drop the list down to select "All" > and then just turn off the apps you don't want to see anything from at all. BTW, you don't have to wait for the toast to go away on its own.
You can call cancel() on this object to cancel it, then show the new one. Show activity on this post. If you'd like to cancel ANY Toast (even if the messages are different), you could leave out the whole currentMessage part and include currentToast != null as a check for cancelling.
You can use the cancel()
method of Toast
to close a showing Toast.
Use a variable to keep a reference to every Toast as you show it, and simply call cancel()
before showing another one.
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 could even wrap that into a small class like so:
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 like so:
SingleToast.show(this, "Hello World", Toast.LENGTH_LONG);
//
Have only one Toast in this activity.
private Toast toast = null;
Then just check if there's currently a Toast
being shown before creating another one.
if (toast == null || !toast.getView().isShown()) {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeToast("Your text", Toast.LENGTH).show();
}
You can even make that last snippet into a private method showToast(text)
to refactor code if you need to display different text messages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With