Android Toast(Java/Kotlin)

This article is about Android Toast and how to use it in android application with simple examples using Java and Kotlin.

Toast

A toast provides simple feedback about an operation in a small popup. 

By default it appears near the bottom of the screen, centered horizontally.

Toasts are not clickable and automatically disappear after a timeout.

Simple Toast

The below code snippet is an example of Simple Toast

//get Toast object
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast", Toast.LENGTH_LONG);

toast.show();  //show Toast

The makeText method (makes a standard toast) takes three parameters:

Context : The context to use (Application or Activity object).

CharSequence: The text to show on Toast.

Duration : How long to display the message. It can be LENGTH_SHORT and LENGTH_LONG.

  • LENGTH_SHORTShow the Toast for a short period of time.
  • LENGTH_LONGShow the Toast for a long period of time.

show(): Used to display the Toast on the screen.

Show standard Toast on click of SIMPLE TOAST button

Positioned Toast

Android Toast allows you to change the position of the Toast using the setGravity() method.

setGravity method accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you want the toast to appear at 400 distance(y-position) from the top-center, you can show the toast with gravity like this:

//get Toast object
Toast toast = Toast.makeText(getApplicationContext(), "Positioned Toast ", Toast.LENGTH_SHORT);
//set toast gravity
toast.setGravity(Gravity.CENTER | Gravity.TOP, 0, 400);
//show toast
toast.show();
Show Toast at specific position on click of POSITIONED TOAST button

Custom Toast

Android Toast allows you to create a customized layout for your Toast.

To create a custom layout, define a View layout, in XML. The following snippet contains a customized layout for Toast (saved as layout/custom_toast.xml):

custom_toast.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/custom_toast_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_background"
    android:padding="@dimen/padding_12dp">

    <ImageView
        android:id="@+id/toast_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/toast_text"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginRight="@dimen/margin_10dp"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/stat_sys_phone_call_on_hold" />

    <TextView
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/custom_toast_text"
        android:textColor="@android:color/black"
        android:textSize="@dimen/textsize_15sp"
        app:layout_constraintBottom_toBottomOf="@+id/toast_img"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/toast_img"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

You must use the ID of the ConstraintLayout element (“custom_toast_container“) and the ID of the XML layout file “custom_toast.xml” to inflate the layout as shown here:

//get View object (using custom layout, created for Toast)
View layout = getLayoutInflater().inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_container));

Now pass this View object to the setView() method.

Toast toast = new Toast(getApplicationContext()); //get Toast object

toast.setDuration(Toast.LENGTH_LONG); //set Toast duration
toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, 300);  //set Toast gravity
toast.setView(layout);  //set View object
toast.show();  //show Toast
Show Toast with Custom View on click of CUSTOM TOAST button

Creating New Project

1. In Android Studio, go to File ⇒ New Project, fill all the details required to create a new project and then click on finish.

2. Rename the layout file activity_main.xml as activity_toast.xml and add the below code. This layout file consist of three buttons, SIMPLE TOAST (To show Android standard toast), POSITIONED TOAST (To show toast at specific position), CUSTOM TOAST (To show toast with custom view).

activity_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/margin_20dp"
tools:context=".ToastActivityKotlin">


<Button
android:id="@+id/btn_simple_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/btn_simple_toast"
android:padding="@dimen/padding_12dp"
app:layout_constraintBottom_toTopOf="@+id/btn_positioned_toast"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />

<Button
android:id="@+id/btn_positioned_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_10dp"
android:layout_marginBottom="@dimen/margin_10dp"
android:text="@string/btn_positioned_toast"
android:padding="@dimen/padding_12dp"
app:layout_constraintBottom_toTopOf="@+id/btn_custom_toast"
app:layout_constraintEnd_toEndOf="@+id/btn_simple_toast"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/btn_simple_toast"
app:layout_constraintTop_toBottomOf="@+id/btn_simple_toast" />

<Button
android:id="@+id/btn_custom_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/btn_custom_toast"
android:padding="@dimen/padding_12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/btn_positioned_toast"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/btn_positioned_toast"
app:layout_constraintTop_toBottomOf="@+id/btn_positioned_toast" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Create a new layout file custom_toast.xml (layout->New->Layout Resource File) and add the below code. This layout file represents the custom layout of toast.

custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/custom_toast_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_background"
    android:padding="@dimen/padding_12dp">

    <ImageView
        android:id="@+id/toast_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/toast_text"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginRight="@dimen/margin_10dp"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/stat_sys_phone_call_on_hold" />

    <TextView
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/custom_toast_text"
        android:textColor="@android:color/black"
        android:textSize="@dimen/textsize_15sp"
        app:layout_constraintBottom_toBottomOf="@+id/toast_img"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/toast_img"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Complete code in Java

Below activity contains three buttons with click listener to show the different ways of implementing the toast in Java.

SnackbarActivityJava.java

package com.c1ctech.androidtoastdemo;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class ToastActivityJava extends AppCompatActivity implements View.OnClickListener {

    private Button btnSimpleToast, btnPositionedToast, btnCustomToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast);

        //get buttons by its id
        btnSimpleToast = findViewById(R.id.btn_simple_toast);
        btnPositionedToast = findViewById(R.id.btn_positioned_toast);
        btnCustomToast = findViewById(R.id.btn_custom_toast);

        //set click listener on buttons
        btnSimpleToast.setOnClickListener(this);
        btnPositionedToast.setOnClickListener(this);
        btnCustomToast.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.btn_simple_toast:
                //show simple toast
                Toast.makeText(getApplicationContext(), "Simple Toast", Toast.LENGTH_LONG).show();
                break;

            case R.id.btn_positioned_toast:
                //get Toast object
                Toast toast = Toast.makeText(getApplicationContext(), "Positioned Toast ", Toast.LENGTH_SHORT);
                //set toast gravity
                toast.setGravity(Gravity.CENTER | Gravity.TOP, 0, 400);
                //show toast
                toast.show();
                break;

            case R.id.btn_custom_toast:

                //get View object (using custom layout, created for Toast)
                View layout = getLayoutInflater().inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_container));

                //get TextView from View object
                TextView text = layout.findViewById(R.id.toast_text);

                //set text in textview
                text.setText("Your phone call is on hold");

                toast = new Toast(getApplicationContext()); //get Toast object

                toast.setDuration(Toast.LENGTH_LONG); //set Toast duration
                toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, 300);  //set Toast gravity
                toast.setView(layout);   //set View object
                toast.show();   //show Toast

                break;

        }
    }
}

When you run the application it will look like this:

Complete code in Kotlin

Create a new activity SnackbarActivityKotlin.kt (New->Activity->Empty Activity->select language kotlin) and then click on finish. This activity contains three buttons with click listener to show the different ways of implementing the toast in Kotlin.

SnackbarActivityKotlin.kt

package com.c1ctech.androidtoastdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class ToastActivityKotlin : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_toast)

        //get buttons by its id
        val btnSimpleToast = findViewById<Button>(R.id.btn_simple_toast)
        val btnPositionedToast = findViewById<Button>(R.id.btn_positioned_toast)
        val btnCustomToast = findViewById<Button>(R.id.btn_custom_toast)

        //set click listener on buttons
        btnSimpleToast.setOnClickListener(this)
        btnPositionedToast.setOnClickListener(this)
        btnCustomToast.setOnClickListener(this)
    }

    override fun onClick(view: View) {

        val id = view.id

        when (id) {

            //show simple toast
            R.id.btn_simple_toast -> Toast.makeText(applicationContext, "Simple Toast", Toast.LENGTH_LONG).show()

            R.id.btn_positioned_toast -> {

                //get Toast object
                val toast = Toast.makeText(applicationContext, "Positioned Toast ", Toast.LENGTH_SHORT)

                //set Toast gravity
                toast.setGravity(Gravity.CENTER or Gravity.TOP, 0, 400)

                //show Toast
                toast.show()
            }
            R.id.btn_custom_toast -> {

                //get View object (using custom layout, created for Toast)
                val layout = layoutInflater.inflate(R.layout.custom_toast, findViewById(R.id.custom_toast_container) as? ViewGroup)

                //get TextView from View object
                val text = layout.findViewById<TextView>(R.id.toast_text)

                //set text in textview
                text.text = getText(R.string.custom_toast_text)   //text.setText("Your phone call is on hold")

                val toast = Toast(applicationContext)  //get Toast object

                toast.duration = Toast.LENGTH_LONG    //set Toast duration

                toast.setGravity(Gravity.CENTER or Gravity.BOTTOM, 0, 300)    //set Toast gravity

                //set View object
                toast.view = layout  //toast.setView(layout)

                toast.show()   //show Toast
            }
        }
    }
}

Leave a Reply