How to show Toast in Android

Create a Android toast or alert message

How to show Toast in Android

To display a message for a little information in your android application we use Toast class in android. An android toast display small message to the users. We can say it's just a little information for the user for few second and disappears after sometime. Normally, android toast is displayed at the bottom of screen but you can also change display position and layout.

 

First of all you require to add Toast class in your activity:

import android.widget.Toast;

 

There are two constants of Toast class which are given below for time duration.

LENGTH_LONG

LENGTH_SHORT

 

 

Example for simple toast:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.legendblogs.demo.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Example of Toast"
        android:id="@+id/textView"
        android:layout_marginTop="91dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me to get Toast"
        android:id="@+id/button"
        android:layout_marginTop="48dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

 

MainActivity.java:

package com.legendblogs.demo;

import android.content.Context;
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 {

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.context = this;

        Button button_toast = (Button) findViewById(R.id.button);

        button_toast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"Hello Legend Blogs User",Toast.LENGTH_SHORT).show();
            }
        });

    }
}

 

 

Top