DEV Community

Cover image for Android Custom Toast With Example
Akshay-Rana-Gujjar
Akshay-Rana-Gujjar

Posted on • Originally published at akshayrana.in

Android Custom Toast With Example

Hello World, today we will be going to see how we can make custom toast and in this tutorial, we will see custom toast with an example. See below as an example.

Custom Toast gif

Before starting let’s see.

What is Toast? When to use it?

Toast is a view that contains text which notifies the user with some information.

We can use toast when we want to notify the user.

Making Custom Toast with Example

To make custom toast we need to follow certain steps as follows.

Step 1. Create a Custom Layout for Toast

the first step is to make a layout file for our toast.

To make a layout file, right-click on layout folder under res and select new -> layout resource file.

we will name this file as custom_toast.xml and in this file, we will make our layout which will b shown in the toast. Check the below code for the layout file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/customToastContainer"
    android:background="#E39D9D"
    android:padding="10sp"
    >

    <ImageView
        android:layout_width="50sp"
        android:layout_height="50sp"
        android:src="@drawable/ic_android"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:id="@+id/toastImage"
        android:tint="@color/colorPrimaryDark"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toastText"
        android:text="Custom Toast"
        android:textSize="30sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@id/toastImage"
        app:layout_constraintBottom_toBottomOf="@id/toastImage"

        />

</androidx.constraintlayout.widget.ConstraintLayout>

In the above code, we set the id to the parent view and we added an imageview and a textview.

We are keeping things simple so that you can understand better.

our layout looks like this below.

Custom toast layout

Step 2. Set layout file to the Toast

To trigger the toast we made a button in the activity layout and calling the makeToast function on click.

Let’s see the code in the makeToast function.

Hey if you want to read full article read here: Android Custom Toast With Example

Top comments (0)