Android Toast With Examples

Toast message is useful to show notification for small time in android app. In this tutorial, we’ll discuss and implement android Toast message example.

Android Toast

Android Toast is used to show notification for a particular interval of time at the bottom of the screen by default. Toast message doesn’t block the user interaction and auto disappears after a timeout. The android.widget.Toast class is the subclass of java.lang.Object class.

Creating a Basic Toast message

Android Toast message is created using the method makeText() that is passed with the context, the message, and the duration as shown below:

The context can be of the application or the activity. It’s recommended to use getApplicationContext() to let the Toast be displayed irrespective of the current state of the Activity.

The duration can be set as Toast.LENGTH_SHORT or Toast.LENGTH_LONG.

The Toast is displayed using the method show().

Positioning your Toast Message

A standard Toast message appears at the bottom of the screen. We can set our own gravity on a Toast as shown below

The second and third parameters are used to shift the toast to the right and down respectively by the offset specified.

Custom Layout for Toast Android

To create a custom layout we can define the view layout in the XML lets say custom_toast.xml

In our activity class, we’ll inflate the above layout and set it on the Toast using the method setView().

Let’s create an application in which each button would display a different type of Toast message, amongst the ones we’ve just discussed.

Android Toast Message Example Project Structure


Android Toast Message Code

The code for the activity_main.xml layout is given below.

The code for the is given below

The output of the android toast example application in action is given below.

Did you notice the position change between the Gravity Toast and the one with Offset included?

This brings an end to toast android tutorial. You can download the final Android Toast Example Project from the link below.

Reference: Official Doc.

By admin

Leave a Reply