Learn how to create and display an Android Toast quickly.

A toast contains a message to be displayed quickly and disappears after some time. The android.widget.Toast class allows you to display a toast that is a view containing a quick little message for the user. Generally, you can use a Toast message to quick debug your application, for example to check whether a button is working properly or not without using the console class.

In this article we will show how to display a regular Toast message easily.

Requirements

The Android Toast is a widget, therefore you need to import it in any class where you want to use it:

import android.widget.Toast;

and in case you want to modify the location of the Toast in the view, import the Gravity class too:

import android.view.Gravity;

import as well the namespace to obtain the context in the code:

import android.content.Context;

You're ready to start with the Android Toast !

The basics

The Toast.makeText method expects as first parameter the context where the toast should be shown, as second parameter the message that will be displayed in the toast and finally as third parameter the duration (short with a value of 0 or Toast.LENGTH_SHORT and long with a value of 1 or Toast.LENGTH_LONG):

Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(context, "Hello World!", duration);
toast.show();

Or do it in a single line:

Toast.makeText(getApplicationContext(), "Hello World!" , Toast.LENGTH_LONG).show();

That should be enough to show a simple toast in your app. Besides, you can change the location of the Toast within the screen by using the setGravity method of the Toast. This method set the location at which the notification should appear on the screen:

Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(context, "Hello World !" , duration);
// Set TOP LEFT in the screen
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();

The previous example should create a toast in the top left of the screen. The possible values for the Gravity constants are Gravity.TOP, Gravity.CENTER, Gravity.BOTTOM, Gravity.RIGHT,Gravity.LEFT.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors