Creating Toast Notifications
Quickview
- A toast is a message that appears on the surface of the screen for a moment, but it does not take focus (or pause the current activity), so it cannot accept user input
- You can customize the toast layout to include images
In this document
Key classes
The screenshot below shows an example toast notification from the Alarm application. Once an alarm is turned on, a toast is displayed to assure you that the alarm was set.

Activity
or Service
. If you create a toast notification from a Service, it appears in front of the Activity currently in focus.If user response to the notification is required, consider using a Status Bar Notification.
The Basics
First, instantiate aToast
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()
, as shown in the following example:Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();This example demonstrates everything you need for most toast notifications. You should rarely need anything else. You may, however, want to position the toast differently or even use your own layout instead of a simple text message. The following sections describe how you can do these things.
You can also chain your methods and avoid holding on to the Toast object, like this:
Toast.makeText(context, text, duration).show();
Positioning your Toast
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with thesetGravity(int, int, int)
method. This 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.
No comments:
Post a Comment