Toast messages is a very popular way of raising a message within an android application to show user a warning, message or an alert.

image

The screenshot below shows an example toast notification from a Twitter application. It displays a Toast that article is posted to Twitter successfully.

image

To show a Toast message First, instantiate a Toast object with one of the makeText() methods having three parameters: the application Context, the text message, and the duration for the toast. This object can be displayed on the Android app screen using the toast notification with the method show(), as shown :

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

 

Toast toastObjectName = Toast.makeText(getBaseContext(), “Article Posted to Twtter successfully”, 5);
toastObjectName .show();

This example demonstrates a Toast that can be posted from your app for 5 seconds duration, with the text as quoted above. Here we are using getBaseContext() to get the defalt context for the class. You can also chain your methods and avoid holding on to the Toast object, like this:

Toast.toast(context, text, duration).show();

Toast Duration have 2 default integers for duration
1) Toast.LENGTH_SHORT – Display the toast for short time to display small notification text.
2) Toast.LENGTH_LONG – Display the toast for long time to display big notification text.

A standard toast notification appears near the bottom of the screen, centered horizontally. If you wish to display Toast in some other position setGravity(int, int, int) method can provide this feature which accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

Make sure you import the following library in your JAVA code to get the things started…

android.widget.Toast

Toast is a nice way to provide user alerts and notification. It can also be used by developers to keep a track of any errors to display some Toast in the exceptions.

One thought on “Displaying a Toast message in Android application”

Leave a Reply

Your email address will not be published. Required fields are marked *