How to hide or cancel Toast message in Android Programming

As you must know that toast message can last for only a SHORT and LONG duration, but if you want to hide a toast message. But what if an event causes the toast messages to pile up and get displayed one after the other cause a bad user experience, so in such situation, it is better to cancel the pending messages queue, here is how we can do it,

Simple toast messages example that shows toast 10 times in a loop!

Toast myToast = null;

    protected void onCreate(Bundle savedInstanceState) {

        for (int i=0;i<=10;i++) {
            myToast = Toast.makeText(MainActivity.this, "Toast message: "+i,Toast.LENGTH_LONG);

How to cancel or hide Toast messages

Button cancelToastButton = (Button) findViewById(;
cancelToastButton.setOnClickListener(new View.OnClickListener() {

 if (myToast != null || myToast.getView().getWindowVisibility() == View.VISIBLE) {


The above code when the button is pressed it should cancel/hide/flush all pending toast messages that are getting displayed.