Working with Toast Messages | Jay Rambhia’s Blog

Working with Toast Messages

I was working on an android application where I required some notification kind of thing. I was looking into popups but it didn’t really work out. Then I stumbled on to Toast Messages.

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive.

The Basics

First, instantiate a Toast object with one of the makeText() methods. This method takes three parameters: the application Context, the text message, and the duration for the toast. It returns a properly initialized Toast object. You can display the toast notification with show().

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);;

The values of LENGTH_SHORT and LENGTH_LONG are 0 and 1. This means they are treated as flags rather than actual durations so I don’t think it will be possible to set the duration to anything other than these values.


I wanted to reduce the the duration of the toast message. I needed it even lesser than LENGTH_SHORT.


Stackoverflow post

Toast.cancel() can be used to shorten the duration of the toast message.

final Toast toast = Toast.makeText(ctx,
                        "This message will disappear in 1 second",

Handler handler = new Handler();

handler.postDelayed(new Runnable() {
    public void run() {
    }, 1000); // time in milliseconds

P.S. Adding small notes is quite fun and helpful.