Toast messages is a very popular way of raising a message within an android application to show user a warning, message or an alert.
The screenshot below shows an example toast notification from a Twitter application. It displays a Toast that article is posted to Twitter successfully.
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.
Very interesting points you have observed , thanks for putting up. “I’ve made a couple of mistakes I’d like to do over.” by Jerry Coleman.