Ghostboard pixel

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:

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        Toast toast = Toast.makeText(getApplicationContext(),"HelloWorld",Toast.LENGTH_LONG);;

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:



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:

Toast toast = Toast.makeText(getApplicationContext(),"HelloWorld",Toast.LENGTH_LONG);

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:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" android:layout_width="match_parent"
        android:text="Hello World!"
        android:id="@+id/textView" />

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

LayoutInflater inflater = getLayoutInflater();
View customToastLayout = inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(;

Toast toast = new Toast(getApplicationContext());

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

LayoutInflater inflater = getLayoutInflater();
        View customToastLayout = inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(;

TextView textView = (TextView) customToastLayout.findViewById(;
textView.setText("HELLO WORLD!!!!");

Toast toast = new Toast(getApplicationContext());


Class reference
Gravity class reference
Title Image: @ Kutsenko Denis /