Click here to Skip to main content
15,881,281 members
Articles / Mobile Apps / Android

Toast: A User Notification

Rate me:
Please Sign up or sign in to vote.
4.83/5 (41 votes)
14 Sep 2010CPOL4 min read 120.9K   2.6K   69   28
How to create different Toasts

Introduction

A Toast is a pop-up message, which allows you to quickly notify the user of some event. E.g. saving settings to an SD Card.

Toast’s distinctive feature is the ability of the user to interact with either the Activity behind it or the Home Screen, while the message is still displayed. It is also noteworthy that the user can't dismiss a Toast using hardware “Back” key or other methods. A message smoothly fades in and then smoothly fades out. The duration between these fades can be set programmatically. In most cases, Toast is just a short message, but you can also create a custom view for it. For example, an image next to the text. Toast’s position on the screen can be controlled as well. Toast can be created from either Activity or Service. If a Toast is created from Service, it is displayed in front of the Activity, which now has the focus, or on top of the Home Screen.

Creating a Standard Toast

A standard Toast can be created by calling a static makeText method of a Toast class.

Java
Toast.makeText(getApplicationContext(), "Hello, The Code Project!",
   Toast.LENGTH_SHORT).show(); 

Application context, the message itself and the duration of the Toast are passed as parameters. You can set the message text as either text or as a resource storing a string to be displayed. In our case, R.string.hello_codeproject resource contains the “Hello, The Code Project!” string. The duration can be either short - LENGTH_SHORT or long - LENGTH_LONG. By default, the duration is set to short. You can programmatically set the duration by calling the setDuration method.

The logic behind makeText method is pretty easy: a Toast object is created and then message text and duration are set. After that, you can either call show method to display the newly created Toast, or set some additional properties, like its position on the screen or a custom view for a Toast. Newly created Toast is shown in the figure below:

toast1.png

Settings the Position of a Toast on the Screen

You can set the position of a Toast on the screen by a call to setGravity method:

Java
Toast toast = Toast.makeText(getApplicationContext(),
   "Hello, The Code Project!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show(); 

The first parameter is used to set the gravity itself (there is a full set of those in Gravity class). Second and third parameters define by how many pixels, relative to the value set in the first parameter, should the Toast be offset. The result of executing the code above is shown in the figure below:

toast2.png

Adding an Image to the Standard Toast

In order to add an image to the standard Toast, you first need to create an ImageView object, and set its image from the resources using the setImageResource method. You then need to get the standard view (which is actually a LinearLayout) and add the newly created ImageView object to it. The position, into which the image needs to be inserted, also should be set (in our case 0 is used, so that the image is displayed over the text). Code for this is shown below:

Java
Toast toast = Toast.makeText(getApplicationContext(),
   "Hello, The Code Project!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.drawable.codeprojectlogo);
toastView.addView(imageCodeProject, 0);
toast.show();

Toast created this way is shown in the figure below:

toast3.png

Creating a Toast with Custom Layout

In order to create a Toast with custom layout, we first need to create that layout itself. Its code is shown below:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="wrap_content" android:layout_width="wrap_content"
	android:background="#ffffffff" android:orientation="vertical"
	android:id="@+id/llToast" >
	<TextView
		android:layout_height="wrap_content"
		android:layout_margin="1dip"
		android:textColor="#ffffffff"
		android:layout_width="fill_parent"
		android:gravity="center"
		android:background="#bb000000"
		android:id="@+id/tvTitleToast" />
	<LinearLayout
		android:layout_height="wrap_content"
		android:orientation="vertical"
		android:id="@+id/llToastContent"
		android:layout_marginLeft="1dip"
		android:layout_marginRight="1dip"
		android:layout_marginBottom="1dip"
		android:layout_width="wrap_content"
		android:padding="15dip"
		android:background="#44000000" >
		<ImageView
			android:layout_height="wrap_content"
			android:layout_gravity="center"
			android:layout_width="wrap_content"
			android:id="@+id/tvImageToast" />
		<TextView
			android:layout_height="wrap_content"
			android:paddingRight="10dip"
			android:paddingLeft="10dip"
			android:layout_width="wrap_content"
			android:gravity="center"
			android:textColor="#ff000000"
			android:id="@+id/tvTextToast" />
	</LinearLayout>
</LinearLayout>

The Toast we created looks like a dialog with a header, an image and a message. We now need to set the layout that we created to the Toast. We should also set the dialog title, the message text and the image. This is how we do it:

Java
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.customtoast,
   (ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast);
image.setImageResource(R.drawable.codeprojectlogo);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("Hello, The Code Project!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

The first two lines initialize the View object by inflating the layout from an XML file (we use an instance of LayoutInflater class, returned by getLayoutInflater, to do that). The first parameter to inflate method sets the id of the layout created earlier - R.layout.customtoast (it matches the res/layout/customtoast.xml file). We then get the references to the image, header title and message text, and fill them with the appropriate data. Finally, we create a Toast itself, set all the required parameters as well as the layout we created earlier (it’s done using setView method). As a result, we get a Toast shown in the figure below:

toast4.png

Calling a Toast from Another Thread

To call a Toast from another Thread, you need to define a property of Handler type in your class:

Java
Handler handler = new Handler();

Now, let’s assume that you have a Thread, in which you need to call a method that displays a Toast:

Java
new Thread(new Runnable() {
   public void run() {
      showToast();
   }
}).start();

In this case, the method will be executed in a separate Thread. But because a Toast can only be displayed in the main Thread, you will get an error when you try to run this.

If you need to execute in the main Thread, when calling from a separate Thread, you need a Handler, that was defined earlier. You can display a Toast from newly created Thread in this way:

Java
public void showToast() {
   handler.post(new Runnable() {
      public void run() {
         Toast.makeText(getApplicationContext(),
            "Hello, The Code Project!", Toast.LENGTH_SHORT).show();
      }
   });
}

That's all.

P.S. Thanks to Timur Dyussebayev for the English translation.

History

  • 14th September, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer JQ Soft
Russian Federation Russian Federation
I'm the Android Software Developer from Moscow, Russia. I have developed MySettings, MyTasks and many other apps for Android

Comments and Discussions

 
QuestionGood Job! Pin
Phebous24-Aug-12 12:37
Phebous24-Aug-12 12:37 
QuestionMy vote is 5 Pin
mohamad yousef10-May-12 1:01
mohamad yousef10-May-12 1:01 
GeneralMy vote of 5 Pin
alwaysabhi01918-Apr-12 18:34
alwaysabhi01918-Apr-12 18:34 
GeneralMy vote of 5 Pin
Samet ÇELİKBIÇAK14-Mar-12 5:10
Samet ÇELİKBIÇAK14-Mar-12 5:10 
GeneralMy vote of 5 Pin
Revon8-Sep-11 5:52
professionalRevon8-Sep-11 5:52 
GeneralMy vote of 5 Pin
maq_rohit31-Jan-11 19:09
professionalmaq_rohit31-Jan-11 19:09 
GeneralMy vote of 5 Pin
Alex Manolescu1-Jan-11 10:23
Alex Manolescu1-Jan-11 10:23 
GeneralMy vote of 1 Pin
Sikh Prashman15-Sep-10 21:24
Sikh Prashman15-Sep-10 21:24 
GeneralRe: My vote of 1 Pin
Maxim Yudin15-Sep-10 21:36
Maxim Yudin15-Sep-10 21:36 
GeneralRe: My vote of 1 Pin
Bill W Benson16-Sep-10 6:16
Bill W Benson16-Sep-10 6:16 
GeneralRe: My vote of 1 Pin
WebMaster30-Dec-12 21:12
WebMaster30-Dec-12 21:12 
GeneralRe: My vote of 1 Pin
Selvin3-Oct-11 13:40
Selvin3-Oct-11 13:40 
GeneralMy vote of 5 Pin
dsurrea15-Sep-10 20:54
dsurrea15-Sep-10 20:54 
GeneralMy vote of 5 Pin
Jackes15-Sep-10 18:40
Jackes15-Sep-10 18:40 
GeneralRe: My vote of 5 Pin
Maxim Yudin15-Sep-10 20:49
Maxim Yudin15-Sep-10 20:49 
GeneralMy vote of 3 Pin
Bill W Benson15-Sep-10 6:04
Bill W Benson15-Sep-10 6:04 
GeneralRe: My vote of 3 Pin
Maxim Yudin15-Sep-10 8:51
Maxim Yudin15-Sep-10 8:51 
GeneralRe: My vote of 3 Pin
portlanderx15-Sep-10 10:08
portlanderx15-Sep-10 10:08 
GeneralMy vote of 5 Pin
Kirtil14-Sep-10 21:36
Kirtil14-Sep-10 21:36 
GeneralRe: My vote of 5 Pin
Marek Paliwoda14-Sep-10 23:45
Marek Paliwoda14-Sep-10 23:45 
GeneralRe: My vote of 5 Pin
Maxim Yudin15-Sep-10 0:00
Maxim Yudin15-Sep-10 0:00 
GeneralThanks Pin
ff0114-Sep-10 21:26
ff0114-Sep-10 21:26 
GeneralRe: Thanks Pin
Maxim Yudin15-Sep-10 0:00
Maxim Yudin15-Sep-10 0:00 
GeneralMy vote of 3 Pin
Evgeny Vinnik14-Sep-10 16:14
Evgeny Vinnik14-Sep-10 16:14 
GeneralMy vote of 5 Pin
BillW3314-Sep-10 14:11
professionalBillW3314-Sep-10 14:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.