Combined solution
In my case, I needed to cancel the current toast, if it is shown, and display another.
This was supposed to solve the scenario when a user requests a service while it is still loading or unavailable. I need to show a toast (maybe I will be different if the requested service is different). Otherwise, the toasts will be displayed in order, and it will take a lot of time to automatically hide them.
So basically I save the toast instance that I create and the following code: how to safely cancel it
synchronized public void cancel() { if(toast == null) { Log.d(TAG, "cancel: toast is null (occurs first time only)" ); return; } final View view = toast.getView(); if(view == null){ Log.d(TAG, "cancel: view is null"); return; } if (view.isShown()) { toast.cancel(); }else{ Log.d(TAG, "cancel: view is already dismissed"); } }
And to use it, now I can not worry about canceling, as in:
if (toastSingleton != null ) { toastSingleton.cancel(); toastSingleton.showToast(messageText); }else{ Log.e(TAG, "setMessageText: toastSingleton is null"); }
showToast is up to you how to implement it, since I need a custom look for my toast.
hannunehg Feb 27 '17 at 10:51 on 2017-02-27 10:51
source share