In this tutorial I am going to discuss you about how to implement toast in android application .

A toast is just a kind o operation that show a simple small popup to the user for better user experience . It is used for showing messages in current activity for short intervals of time and the current activity remain visible .
Toasts automatically disappear after some duration of time . The default Toast’s view contains a TextView for showing messages on it.

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to implement toast in android app .

1. Create a button to your main layout file :

Now we create a button to your main layout file i.e. activity_main.xml of your Main_Activity.java file or just implement the following xml code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Btn"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"/>
    
</LinearLayout>

2.  Now open your MainActivity.java and add following code :

Here we create a Toast with one of the makeText( ) methods. This method takes three parameters: the application Context , the text message, and the duration for the toast. It returns a properly initialised Toast message. You can display the toast notification with show( ) method .

package com.technxtcodelabs;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
    Button btn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create a Toast message here
                Toast.makeText(getApplicationContext(),"Your message here",Toast.LENGTH_SHORT).show();
                
            }
        });

    }  
}

You can also customise toast with adding an image to it and changing size, colour of the message text .

Now run the project/app to test toast in android app through android device or any Emulator .

%d bloggers like this: