A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.
For example, clicking Send on an email triggers a "Sending message..." toast, as shown in the following screen capture:
Alternatives to using toasts
If your app is in the foreground, consider using a snackbar instead of using a toast. Snackbars include user-actionable options, which can provide a better app experience.
If your app is in the background, and you want users to take some action, use a notification instead.
Instantiate a Toast object
method, which takes the following parameters:
- The application
- The text that should appear to the user.
- The duration that the toast should remain on the screen.
makeText() method returns a properly initialized
Show the toast
To display the toast, call the
method, as demonstrated in the following example:
val text = "Hello toast!" val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(applicationContext, text, duration) toast.show()
Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();
Chain your toast method calls
You can chain your methods to avoid holding on to the
object, as shown in the following code snippet:
Toast.makeText(context, text, duration).show()
Toast.makeText(context, text, duration).show();