Android – custom Toast notification

By -

Problem: How to create a custom Toast notification?

Solution:

First, if you don’t know about Toast notification in android, then I would suggest you to go through the previous article on: Text notifications (Toast). In this article, we will look into how to define a custom Toast notification, to show a notification with image and text.

Example:
Create one XML layout file and give a name cust_toast_layout.xml and define the below layout.

cust_toast_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/relativeLayout1"
  android:background="@android:color/white">

    <TextView
    	android:textAppearance="?android:attr/textAppearanceLarge"
    	android:id="@+id/textView1" android:layout_height="wrap_content"
    	android:layout_width="fill_parent"
    	android:text="Paresh N. Mayani"
    	android:gravity="center"
    	android:textColor="@android:color/black">
    </TextView>

    <ImageView
    	android:layout_height="wrap_content"
    	android:layout_width="fill_parent"
    	android:src="@drawable/new_logo"
    	android:layout_below="@+id/textView1"
    	android:layout_margin="5dip"
    	android:id="@+id/imageView1">
    </ImageView>

    <TextView
    	android:id="@+id/textView2"
    	android:layout_height="wrap_content"
    	android:layout_width="fill_parent"
    	android:text="This is the demo of Custom Toast Notification"
    	android:gravity="center"
    	android:layout_below="@+id/imageView1"
    	android:textColor="@android:color/black">
    </TextView>

</RelativeLayout>

Now, inflate the above layout to create/show custom Toast notification.

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.cust_toast_layout,
                                       (ViewGroup) findViewById(R.id.relativeLayout1));

        Toast toast = new Toast(this);
        toast.setView(view);
        toast.show();
Paresh Mayani

Lazy android developer, exploring the horizon of android development since 7 years, currently working as a Technical Lead - Android at Simform Solutions, India. Former Application Architect at KarConnect. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...