Android custom toast example

In android, it is easy to display toast by using a single line of code, but what if we want to display an imageview inside a toast.  You can implement it by using custom toast. In this tutorial we will learn how to implement a custom toast with imageview in android.

First step is  to have a layout which we should display in toast. Create a new xml file under res/layout

Note: For using the below code you need to have an image named android.png file in your res/drawable  folder or you can use any image file, but replace the name with your file name in following code

custom_toast_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/custom_toast">


<ImageView
android:id="@+id/im_taost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/android"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is android custom toast with imageview"
android:layout_below="@+id/im_taost"/>

</RelativeLayout>

Now simply use the below code in your Activity class file, whenever you want to display toast

View layout = getLayoutInflater().inflate(R.layout.custom_toast_layout, (ViewGroup) findViewById(R.id.custom_toast));

Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);// you can set LENGTH_SHORT also
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(layout);
toast.show();
android-custom-toast
android-custom-toast

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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