
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 –
- The context (In the example code below I have passed the activity context)
- The text (message) you want to show to the user
- 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