Android Custom Toast
Post
Cancel

Custom Toast

A toast is a view containing a quick little message for the user. It will never receive focus and will be dismiss after a specific time.

By default, if you want to call a simple Toast, all you need is just one line of code:

Toast.makeText(context, text, duration).show();

And you will get the result like this:

Custom Toast

More than that, this entry will show you how to customize a Toast with your own layout and style!

Firstly, create your desired layout for the custom toast:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout"
    android:background="#99CC00"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/imgIcon"
        android:text="Message"
        android:textColor="#FFFFFF"
        android:layout_marginLeft="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

With those XML code, you will have a toast like this:

Custom Toast

In the code behind, we need to handle all the controls in custom layout:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
        (ViewGroup) findViewById(R.id.custom_toast_layout));
TextView tvMesage = (TextView)layout.findViewById(R.id.tvMessage);
tvMesage.setText("OMG! This custom toast is awsome!");

Next, create a new Toast object, set the custom View for it and do some settings like gravity, duration:

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 10, 10);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);

Finally, do not forget to show it!

toast.show();

And, tada! Show time!

Source code:

https://drive.google.com/file/d/0BzvV1wN-WHWwdmphRUJHTHdndXM/edit?usp=sharing

This post is licensed under CC BY 4.0 by the author.