What is Toast and how to create Toast in android?

In this post, we are going to learn about Toast. We will see what is a Toast in android and how can you create Toast in android. So, let’s begin.

What is Toast in android?

Toast appears on the screen as a small popup. When you want to show a message to the user for some specified duration then you can use Toast. It will disappear automatically after the specified duration.

How to create a Toast?

To create a Toast we use MakeText() method and pass the following parameters –

  1. The context (In the example code below I have passed the activity context)
  2. The text (message) you want to show to the user
  3. The duration that the toast should remain visible on the screen.

So we will make Toast like this – Toast.MakeText(this, “This is a toast”, Toast.LENGTH_SHORT)

(See the example code below.)

Let’s see an example.

MainActivity.java

package com.example.toastexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Make toast
        Toast toast=Toast.makeText(this, "This is a toast", Toast.LENGTH_SHORT);

        //Show toast
        toast.show();
    }
}

activity_main.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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output :

You can see the Toast at the bottom of the screen in the screenshot above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: