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.



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap