Sunday, February 14, 2010

Want to display a quick message to your users? Use some Toast!

A toast is a notification view that contains a quick little message for the user. All it does is display the message, it's not interactive at all.

The toast class helps you create and show those.

When this view is shown to the user, it appears to float over the application. It will never receive focus as the user may be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the information you want them to see. Two possible examples are a volume control, and a brief message saying that your settings have been saved.

The easiest way to use this class is to call one of the static methods that constructs everything you need and returns a new Toast object.

A piece of toast is typically a simple text message, an image, or a combination of text and image.
You don't have control on the toast duration. There are only two states LENGTH_LONG and LENGTH_SHORT.

For this example we have added an image to one of the drawable folders under 'res' in our project, we refer to it simply like this:


Our image is actually called flash.png, note that we don't need to include the 'png' extension in our Android code, it already knows what we're talking about ;)

Here are 3 methods, demonstrating the above.

First, just show an image:

private void imageToast()
Toast toast = new Toast(getApplicationContext());
ImageView view = new ImageView(getApplicationContext());

This method just displays a text toast:

public void textToast(String textToDisplay) {
Context context = getApplicationContext();
CharSequence text = textToDisplay;
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);;

.. And this method displays a Toast that contains both an image and text:

public void textAndImageToast(String textToDisplay)
Toast toast = Toast.makeText(getApplicationContext(), textToDisplay, Toast.LENGTH_LONG);
View textView = toast.getView();
LinearLayout lay = new LinearLayout(getApplicationContext());
ImageView view = new ImageView(getApplicationContext());

You can call each of these like this:

textToast("This is a text toast");

textAndImageToast("This is a text and image toast");

And here are the results:

A text Toast

A text & image Toast

this is an image Toast

Here is the same image Toast with default Gravity for better demonstration purposes

Hope that makes sense.
.. Till next time, happy coding :)

No comments:

Post a Comment