Friday, June 17, 2011

Displaying an Android Toast

This tutorial describes how to display a toast in an Android Application.

What is a Toast?

A toast is a small message that pops up at the bottom of the user's Android device. Shown below is a screenshot of a toast. Toasts differ from message boxes in the fact that they don't take focus, so they are less intrusive.

Screenshot of an app displaying a toast.

Why use a Toast?

Toasts can be useful for displaying a short message or a small amount of information to the user. Toasts are also shown on top of everything else on the screen.

Toasts can be extremely useful for informing the user that an action has occurred independent of what Activity is currently shown on your stack.

A good example of this is with an e-mail application. After clicking the send button, the "Compose Message" activity will immediately disappear, and the user is returned to the inbox activity. A toast appears to let the user know that the message was sent.

Code to Display a Toast

Displaying a toast is fairly straightforward.

// Display a toast!
Toast.makeText(getBaseContext(), "Hello, Toast!", Toast.LENGTH_LONG).show();

And that's it. Of course, you don't have to call show right away, and can save a reference to the toast object if you like.

1 comment: