I have read about this kind of problem here but the answers don't seem to be working.
I show a Toast
when user clicks a button. When the user continously clicks the button the toast keeps on being displayed again and again even when the user exits the activity.
The length of the toast is short. Length of the toast cannot be changed as the text is long.
This is what i have tried as of now:
Toast toast;
toast=Toast.makeText(getApplicationContext(),"text",Toast.LENGTH_SHORT);
if(toast.getView().isShown()==false){
toast.show();
}
This did not work.
I tried :
if(toast.getView().isShown()==true){
toast.cancel();
}
in the onStop()
. For some reason the cancel method never works.
If i put the .cancel()
before i show the app... then there would be another null check for that. But after doing that also it did not work. I can show a dialog box instead of a toast but that would not be a solution.
Is there any way to check whether a toast is being displayed or not?
For reference
Toast Message in Android
How to avoid a Toast if there's one Toast already being shown
How to prevent Multiple Toast Overlaps
Cancelling an already open toast in Android
How do you avoid a toast if there's one toast already being shown? 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.
Toast. makeText returns a Toast object. Call cancel() on this object to cancel it.
You can use toast. cancel() befor showing next toast. cancelling won't reduce the toast time.
If you call toast. dismiss without argument, all the displayed toasts will be removed.
Instead of cancelling the toast. change the text. For Example
Toast t;
t = Toast.makeText(this, "hi", 3000);
t.show();
when you need a different toast then use
t.setText("bye");
t.show();
And If you want to dismiss the toast simply call t.cancel()
Try keeping the timestamp of the last toast, and don't allow any new toasts until a timeout period has elapsed.
Something like:
private static final long TOAST_TIMEOUT_MS = 2000; // tweak this constant
private static long lastToastTime = 0;
public void onButtonClicked() {
long now = System.currentTimeMillis();
if (lastToastTime + TOAST_TIMEOUT_MS < now) {
Toast.makeText(...).show();
lastToastTime = now;
}
}
I wouldn't worry about a single toast sticking around for a second after the user exits the app -- this is a pretty standard behavior.
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