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.

Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.