android toast

Android: Toast

On Android, a toast is used to display a short notice. For example, this could be the confirmation that an action has been completed successfully, like adding a favorite. 

Let’s start by displaying a simple toast. You create a toast by using the static method makeText of the Toast class. The method show() displays the toast:

In this example, we are displaying the toast immediately after the activity has been created. In a real world application this doesn’t make a lot of sense in most cases, but for a simple example that’s absolutely sufficient.

After starting the app, the toast is appears and then disappears after a few seconds:

android toast

As a side note there is to mention that out of the box there’s nothing comparable on iOS. If you want to implement something like that on iOS you can do it manually though, or, using a third-party library like Whisper.

Duration Length

There are two duration lengths you can choose from: Toast.LENGTH_LONG and Toast.LENGTH_SHORT. You can not only set it at initialisation time of the Toast, but also afterwards:

Position

In order to position the toast on the screen, you can use the method setGravity (int gravity, int xOffset, int yOffset) on a Toast object.

Besides two values for offsets, it also takes a constant from the Gravity  class. For example, if you want to place toast in the centre of the screen, you can do it as following:

There are many other possible values like Gravity.LEFT, Gravity.RIGHT, Gravity.TOP and Gravity.BOTTOM.

Custom Toasts

It’s also possible to create a custom view for a toast. For that, we first have to create a new layout:

The XML is called custom_toast.xml. Now, we can inflate the layout and set it as the toast’s view:

Of course you can also access the layout’s elements:

References

Class reference
Gravity class reference
Title Image: @ Kutsenko Denis / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon