Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Android | What is Toast and How to use it with Examples

  • Difficulty Level : Medium
  • Last Updated : 01 May, 2019

Pre-requisites:

This article aims to tell What is Toast and How to use it to display messages in an android app.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

What is Toast in Android?

A Toast is a feedback message. It takes a very little space for displaying while overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If user wants permanent visible message, Notification can be used.

Another type of Toast is custom Toast, in which images can be used instead of a simple message.



Example:

Toast class: Toast class provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity).

Constants of Toast class

ConstantsDescription
public static final int LENGTH_LONGdisplays for a long time
public static final int LENGTH_SHORTdisplays for a short time


Methods of Toast class

MethodsDescription
public static Toast makeText(Context context, CharSequence text, int duration)makes the toast message consisted of text and time duration
public void show()displays a toast message
public void setMargin (float horizontalMargin, float verticalMargin)changes the horizontal and vertical differences

How to create an Android App to show a Toast message (with Example)

In this example “This a simple toast message” is a Toast message which is displayed by clicking on ‘CLICK’ button. Every time when you click your toast message appears.

Steps to create an Android Application with Toast Message:

  • Step 1: Create an XML file and a Java File. Please refer the pre-requisites to learn more about this step.
  • Step 2: Open “activity_main.xml” file and add a Button to show Toast message in a Constraint Layout.

    Also, Assign ID to button component as shown in the image and the code below. The assigned ID to the button helps to identify and to use in Java files.



    android:id="@+id/id_name"

    Here the given ID is Button01

    This will make the UI of the Application.

  • Step 3: Now, after the UI, this step will create the Backend of the App. For this, Open “MainActivity.java” file and instantiate the component (Button) created in the XML file using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
    General Syntax:

    ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);

    Syntax for used component (Click Button):

    Button btn = (Button)findViewById(R.id.Button01);

  • Step 4: This step involves setting up the operations to display the Toast Message. These operations are as follows:
    1. Add the listener on Button and this Button will show a toast message.

      btn.setOnClickListener(new View.OnClickListener() {});

    2. Now, Create a toast message. The Toast.makeText() method is a pre-defined method which creates a Toast object.

      Syntax:

      public static Toast makeText (Context context, 
                      CharSequence text, 
                      int duration)
      

      Parameters: This method accepts three parameters:

      • context: The first parameter is a Context object which is obtained by calling getApplicationContext().
         Context context = getApplicationContext(); 
      • text: The second parameter is your text message to be displayed.
        CharSequence text=”Your text message here”
      • duration: The last parameter is the time duration for the message.
        int duration=Toast.LENGTH_LONG;

      Therefore the code to make a Toast message is:

      Toast.makeText(getApplicationContext(),
                     "This a toast message",
                     Toast.LENGTH_LONG);
      

    3. Display the created Toast Message using the show() method of the Toast class.

      Syntax:



      public void show ()

      The code to show the Toast message:

      Toast.makeText(getApplicationContext(),
                     "This a toast message",
                     Toast.LENGTH_LONG)
           .show();
      

  • Step 5: Now Run the app and operate as follows:
    • When the app is opened, it displays a “Click” button.
    • Click the Click button.
    • Then “This a toast message” will be displayed on the screen as a Toast Message.

Complete Code to display a simple Toast Message:

activity_main.xml




<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
 <!-- add button for generating Toast message -->
    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="209dp"
        android:onClick="onClick"
        android:text="Click"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="OnClick" />
  
</android.support.constraint.ConstraintLayout>

MainActivity.java




package org.geeksforgeeks.simpleToast_Example;
  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
public class MainActivity extends AppCompatActivity {
  
    // Defining the object for button
    Button btn;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Bind the components to their respective objects
        // by assigning their IDs
        // with the help of findViewById() method
        Button btn = (Button)findViewById(R.id.Button01);
  
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                // Displaying simple Toast message
                Toast.makeText(getApplicationContext(),
                               "This a toast message",
                               Toast.LENGTH_LONG)
                    .show();
            }
        });
    }
}

Output:

How to change the position of a Toast message (with Example)

If there is a need to set position of a Toast message, then setGravity() method can be used.

public void setGravity (int gravity, 
                int xOffset, 
                int yOffset)

Parameters: This method accepts three parameters:

  • gravity: This sets the position of the Toast message. Following constants can be used to specify the position of a Toast:
    1.TOP
    2.BOTTOM
    3.LEFT
    4.RIGHT
    5.CENTER
    6.CENTER_HORIZONTAL
    7.CENTER_VERTICAL
    

    Every constant specifies the position in X and Y axis, except CENTER constant which sets position centered for both horizontal and vertical direction.

  • xOffset: This is the offset value that tells how much to shift the Toast message horizontally on the x axis.
  • yOffset: This is the offset value that tells how much to shift the Toast message vertically on the y axis.

For example:

1. To display the Toast at the center:

toast.setGravity(Gravity.CENTER, 0, 0);

2. To display the Toast at the top, centered horizontally:



toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 0);

3. To display the Toast at the top, centered horizontally, but 30 pixels down from the top:

toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 30);

4. To display the Toast at the bottom, rightmost horizontally:

toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);

Example: Here, in the below example, the Toast is displayed at the Bottom-Right position.

Syntax:

Toast t = Toast.makeText(getApplicationContext(),
                         "This a positioned toast message",
                         Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
t.show();

Complete Code:

activity_main.xml




<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
 <!-- add a button to display positioned toast message -->
    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="209dp"
        android:onClick="onClick"
        android:text="Click"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="OnClick" />
  
</android.support.constraint.ConstraintLayout>

MainActivity.java




package org.geeksforgeeks.positionedToast_Example;
  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
public class MainActivity extends AppCompatActivity {
  
    // Defining the object for button
    Button btn;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Binding the components to their respective objects
        // by assigning their IDs
        // with the help of findViewById() method
        Button btn = (Button)findViewById(R.id.Button01);
  
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
  
                // Displaying posotioned Toast message
                Toast t = Toast.makeText(getApplicationContext(),
                                         "This a positioned toast message",
                                         Toast.LENGTH_LONG);
                t.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
                t.show();
            }
        });
    }
}


Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :