In my app, I construct a calendar widget for my activity, when I scroll it to previous or next month, I let it make a toast and show it.
The question is, the toast n
Here is the Code.
final Toast toastobject = Toast.makeText(context, "This message will disappear when toast.close(); is called", Toast.LENGTH_SHORT);
Now you can use the Object of toastobject. Its Reference
toastobject.cancel();
You can use it in Thread or whenever you would like to Close the Toast.
You need to call method on correct object.
toastObject.cancel()
You can reuse a toast, this will make it display immediately.
myToast.setText(toastMsg);
myToast.show();
There are many ways by which we can cancel previous Toast when we want to show another Toast. below I have written a simplest an easy way to implement it. First of all, we have to create a variable which can be accessed in the whole class.
private Toast toast;
After creating the variable which can be accessed by whole class we have to create a method in our class which displays the toast message and checks if the previous toast is displaying then cancel it.
public void showToast(String message) {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
you can change toast message by runtime calling above method.
showToast("message 1");
//after some time
showToast("message 2");
hope it helps.
You can create static method and use it to show a toast:
public static Toast toast = null;
public static showToast(Context context,String msg){
if(toast!=null) //this will cancel the toast on the screen if one exists
toast.cancel();
toast = Toast.makeText(context,msg);
toast.show();
}
You just need to declare a "Toast" var like this:
Toast toastMessage;
Then in your function, do it like this:
if (toastMessage!= null) {
toastMessage.cancel();
}
toastMessage= Toast.makeText(context, "The message you want to display", duration);
toastMessage.show();