Android Custom Toast Example

Toast is a mechanism used to display information in Android. Unlike Dialog, Toast has no focus, and the show time is limited. Toast message will disappear automatically after a certain amount of time. So Toast is generally used to display prompt messages to users.

1. How To Use Toast.

  1. Uset Toast.makeText() method.
    Toast toast = Toast.makeText(getApplicationContext(), "Default Toast Style", Toast.LENGTH_SHORT);
  2. Use Toast Constructor. But you need to call Toast.setView(View view) method to set it’s content view. You also need invoke it’s other methods to set related properties.
    Toast toast = new Toast(getApplicationContext());
    // Set custom view in toast.
    toast.setView(toastView);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0,0);
  3. How to show Toast prompt.
    toast.show();

2. Custom Toast Example.

android custom toast example

2.1 Main Layout Xml File.

The main screen contains five buttons. Each button will prompt a different Toast message when clicked.

activity_toast.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/defaultToastButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Default Toast" />

    <Button
        android:id="@+id/locationToastButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Custom Toast Location" />

    <Button
        android:id="@+id/imageToastButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Toast With Image" />

    <Button
        android:id="@+id/customToastButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Custom Toast" />

    <Button
        android:id="@+id/childThreadToastButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Child Thread Toast" />
</LinearLayout>

2.2 Activity Java File.

This file includes 5 methods, each method include java code that prompt a custom Toast.

ToastActivity.java

package com.dev2qa.example;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ToastActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com --- Android Toast Example");

        this.showDefaultToast();

        this.showToastInLocation();

        this.showImageInToast();

        this.showFullyCustomToast();

        this.showChildThreadToast();
    }
}

2.3 Default Toast Example.

default toast style

// Show default Toast prompt.
private void showDefaultToast()
{
    Button toastButton = (Button)findViewById(R.id.defaultToastButton);
    toastButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast toast = Toast.makeText(getApplicationContext(), "Default Toast Style", Toast.LENGTH_SHORT);
            toast.show();
        }
    });
}

2.4 Show Toast Prompt In Specified Location.

custom toast location

// Show Toast prompt in a specified location.
private void showToastInLocation()
{
    Button toastButton = (Button)findViewById(R.id.locationToastButton);
    toastButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast toast = Toast.makeText(getApplicationContext(), "Custom Toast Location", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 100,100);
            toast.show();
        }
    });
}

2.5 Show Image In Toast Prompt.

show image in toast

// Show images in Toast prompt.
private void showImageInToast()
{
    Button toastButton = (Button)findViewById(R.id.imageToastButton);
    toastButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast toast = Toast.makeText(getApplicationContext(), "Show Image In Toast", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            LinearLayout toastContentView = (LinearLayout) toast.getView();
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageResource(R.drawable.if_snowflake);
            toastContentView.addView(imageView, 0);
            toast.show();
        }
    });
}

2.6 Custom Toast View Content.

fully custom toast

// Fully customize Toast view content.
private void showFullyCustomToast()
{
    Button toastButton = (Button)findViewById(R.id.customToastButton);
    toastButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Get the custom layout view.
            View toastView = getLayoutInflater().inflate(R.layout.activity_toast_custom_view, null);

            // Initiate the Toast instance.
            Toast toast = new Toast(getApplicationContext());
            // Set custom view in toast.
            toast.setView(toastView);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0,0);
            toast.show();
        }
    });
}

This example also need below two files.

READ :   Android ActionBar Spinner (Dropdown List) Example

activity_toast_custom_view.xml

This is the custom view object that will be displayed in Toast prompt message. This file is saved in app / res / layout folder.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/custom_toast_background"
    android:padding="10dp">

    <ImageView
        android:id="@+id/customToastImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/message_block"/>

    <TextView
        android:id="@+id/customToastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fully custom toast."
        android:textSize="20dp"/>

</LinearLayout>

custom_toast_background.xml

This is a custom shape that is used as above custom view’s background. This file is saved in app / res / drawable folder.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <solid android:color="@android:color/holo_green_light" />

    <corners android:radius="15dp" />

</shape>

2.7 Toast Message From Child Thread.

toast from child thread

public class ToastActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com --- Android Toast Example");

        this.showChildThreadToast();
    }

    // Below code are used to display Toast message from child thread.

    // This variable is used to identify where the message is come from.
    private int SHOW_TOAST_MESSAGE = 1;

    // This Handler is used to handle message from child thread.
    private Handler toastActivityHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == SHOW_TOAST_MESSAGE)
            {
                Toast toast = Toast.makeText(getApplicationContext(), "Toast From Child Thread.", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL, 10, 10);
                toast.show();
            }
        }
    };

    private void showChildThreadToast()
    {
        Button toastButton = (Button)findViewById(R.id.childThreadToastButton);
        toastButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Create a child thread.
                Thread childThread = new Thread(){
                    @Override
                    public void run() {
                        // Send message from child thread to main thread.
                        Message msg = new Message();
                        msg.what = SHOW_TOAST_MESSAGE;
                        toastActivityHandler.sendMessage(msg);
                    }
                };

                // Start the thread.
                childThread.start();
            }
        });
    }

}

4 Comments


  1. Why do we use findviewbyid inside inflate method in custom toast?

    Reply

    1. We use findViewById to get the button object, then add onClick event to each button object to show difference toast message.

      Reply

  2. Looks really good and works just fine..
    Thank you

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.