MY mENU


Tuesday 13 March 2012

Toast message in Android

Toast is a transient message that appears and disappears without any interaction from the user and with no notification to the program that it disappeared. The Toast can display a simple text message or a complex view.


Displaying simple text: To display a simple toast that displays a text message we use the following code:
1Toast toast=Toast.makeText(this"This is toast message"2000);
2     toast.setGravity(Gravity.TOP, -3050);
3     toast.show();
we create the toast using the static Toast.makeText(Context con,String message, int duration) method to create a toast in the current context to display a text message for a duration specified in milli seconds or we can use the constant values Toast.LENGTH_SHORT to display for a short duration or Toast.LENGTH_LONG for longer duration. The toast by default appears in the center of the screen, you can change the default position by specifying the Gravity and the X and Y offsets. finally we call the Show() method to display the toast.



Displaying complex views: Toasts can also display complex views. this is done like this:

First: create a layout xml file in res/layout directory. the file must be named toast_layout.xml.
01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    android:orientation="vertical"
04    android:layout_width="fill_parent"
05    android:layout_height="fill_parent"
06    android:id="@+id/toastView"
07    >
08<TextView 
09    android:layout_width="fill_parent"
10    android:layout_height="wrap_content"
11    android:text="Hello toast"
12    android:textColor="#000"
13    />
14    <TextView 
15    android:layout_width="fill_parent"
16    android:layout_height="wrap_content"
17    android:id="@+id/txtDate"
18    android:textColor="#000"
19    />
20    
21     
22</LinearLayout>
then from the code
1Toast toast=new Toast(this);
2     LayoutInflater inflater=this.getLayoutInflater();
3     View toastView=inflater.inflate(R.layout.toast_layout, (ViewGroup)findViewById(R.id.toastView));
4     TextView txtDate=(TextView)toastView.findViewById(R.id.txtDate);
5     txtDate.setText("toast appeared at "+Calendar.getInstance().getTime().toLocaleString());
6     toast.setGravity(Gravity.CENTER, 00);
7     toast.setView(toastView);
8     toast.show();

the toast will be like this:
Notes:
  • In the toast_layout.xml width, if you put any buttons or any control that has a callback, it would appear disabled and the user cannot interact with it.
  • The toast can be created in two ways: by calling Toast.makeText method or by specifying a view via setView method. when you want to display a simple text use the first one otherwise use the second. if you try to interchange or combie between the two methods an exception will be thrown.

No comments:

Post a Comment