androidandroid-toast

How to avoid a Toast if there's one Toast already being shown


I have several SeekBar and onSeekBarProgressStop(), I want to show a Toast message.

But if on SeekBar I perform the action rapidly then UI thread somehow blocks and Toast message waits till UI thread is free.

Now my concern is to avoid the new Toast message if the Toast message is already displaying. Or is their any condition by which we check that UI thread is currently free then I'll show the Toast message.

I tried it in both way, by using runOnUIThread() and also creating new Handler.


Solution

  • 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
        }