Android custom toasts - varshaAv/Android-Tutorials GitHub Wiki

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.

and also we can create custom toast in android.so, we can add some images, layouts, margins, etc to our toast. in short we can customize it.

The Basic

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

Positioning of toast

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

Custom Toast view

We can create customize layouts for our toast notifications.To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView(View) method.

For Example: res/layout/toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/custom_toast_container"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="8dp"
          android:background="#DAAA"
          >
<ImageView android:src="@drawable/droid"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginRight="8dp"
           />
<TextView android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          />

So, out activity will contain following code:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
            (ViewGroup) findViewById(R.id.custom_toast_container));// inflate the layout from xml

TextView text = (TextView) layout.findViewById(R.id.text);//textview to be added in toast
text.setText("This is a custom toast");//setting text on above textview

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);//setting gravity
toast.setDuration(Toast.LENGTH_LONG);//setting duration
toast.setView(layout);//finally setting layout to the toast
toast.show();//showing or displaying the toast