Best way to avoid Toast accumulation in Android
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);
//
Remove multiple toast?
I haven't tried it for real but I suspect just cancelling it on the next click and making a new one would be alright.
Toast mToast;
public void onContentChanged() {
...
button.setOnClickListener(toastListener);
OnClickListener toastListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
mToast.show();
}
};
Preventing Toasts from queueing up
Toast.makeText(...)
is static member of Toast
class returning Toast
instance. You've declared Toast lToast
object but you didnt initialize it.
Change:
lToast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
to
lToast = Toast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
I'm not sure if this will work, but it will prevent raising NullPointerException
.
Problem with display multiple Toast in order one after another
but only second toast message will appear. i think when show method of
second toast will execute it will cancel previous toast (first toast)
When you call show
method, it will put into message queue of UI thread, and the Toast will be shown in order. But you put two Toast at the same time, the latter will overlap the former.
i want show two toast in order, in other word when first toast
duration is over second toast appear.
From Toast duration
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
To make the second toast display after duration of the first one, change your code to
Toast.makeText(this, "Toast1", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
Toast.makeText(MainActivity.this, "Toast2", Toast.LENGTH_SHORT).show();
}
}, 2000);
but is there any easier solution?
Using Handler is the easy and simple solution to achieve your task.
How to immediately replace the current toast with a second one without waiting for the current one to finish?
You can cache current Toast
in Activity's variable, and then cancel it just before showing next toast. Here is an example:
Toast m_currentToast;
void showToast(String text)
{
if(m_currentToast != null)
{
m_currentToast.cancel();
}
m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
m_currentToast.show();
}
Another way to instantly update Toast
message:
void showToast(String text)
{
if(m_currentToast == null)
{
m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
}
m_currentToast.setText(text);
m_currentToast.setDuration(Toast.LENGTH_LONG);
m_currentToast.show();
}
Prevent duplicate Toast messages in Ionic
You can use a property on that page to know if a toast is being shown or not before showing a new one.
Ionic 2/3
import { ToastController, Toast } from 'ionic-angular';
// ...
private isToastVisible: boolean;
constructor(private toastCtrl: ToastController) { }
presentToast() {
if(this.isToastVisible) {
return;
}
this.isToastVisible = true;
const toast: Toast = this.toastCtrl.create({
message: 'User was added successfully',
duration: 3000,
position: 'top'
});
toast.onDidDismiss(() => {
this.isToastVisible = false;
});
toast.present();
}
Ionic 4/5
import { ToastController } from '@ionic/angular';
// ...
private isToastVisible: boolean;
constructor(private toastCtrl: ToastController) { }
presentToast() {
if(this.isToastVisible) {
return;
}
this.isToastVisible = true;
this.toastCtrl.create({
message: 'User was added successfully',
duration: 3000,
position: 'top'
}).then((toast: HTMLIonToastElement) => {
toast.onDidDismiss().then(() => {
this.isToastVisible = false;
});
toast.present();
})
}
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
}
Related Topics
Can Not Set Debuggable Flag in Androidmanifest.Xml
Android SQLite Selection Args[] with Int Values
Checkbox Gets Unchecked on Scroll in a Custom Listview
How Can One Pull the (Private) Data of One's Own Android App
How to Programmatically Log Out from Facebook Sdk 3.0 Without Using Facebook Login/Logout Button
Room Cannot Verify the Data Integrity
Change Navigationview Items When User Is Logged
How to Prevent Multiple Toast Overlaps
How Are Android Activities Handled with Jetpack Compose and Compose Navigation
Is Deprecated Word the Only Difference Between Fill_Parent and Match_Parent
Ndk: How Include *.So Files in Androidstudio
Java.Lang.Noclassdeffounderror: Org.Ksoap2.Serialization.Soapobject
I Want My Android Application to Be Only Run in Portrait Mode
Finding the Dominant Color of an Image in an Android @Drawable
Android: How Handle Message Error from the Server Using Volley