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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

How to cancel or hide Toast messages

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

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

});

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




Recent Posts:




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, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.