Fork me on GitHub

Working with Toast Messages

Posted on 24 January 2014
Under Notes
Tagged
Android

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);
toast.show();

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.

Problem

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

Solution

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",
                        Toast.LENGTH_SHORT);
toast.show();

Handler handler = new Handler();

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

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

comments powered by Disqus


If you have some feedback or questions regarding this post, please add comments. I'd be happy to get some feedback.



If you liked this post, then you should follow Jay on twitter too. He would be excited to know that you like his work.