Android popup messages using Toast

Public on September 1, 2010
In Android you can display pop up messages that lasts for a certain duration and then disappears-using the Toast class.

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:
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.setGravity(Gravity.TOP, -30, 50);
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.

the previous toast will be like this:

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.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/toastView"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello toast"
android:textColor="#000"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txtDate"
android:textColor="#000"
/>


</LinearLayout>

then from the code
Toast toast=new Toast(this);
LayoutInflater inflater=this.getLayoutInflater();
View toastView=inflater.inflate(R.layout.toast_layout, (ViewGroup)findViewById(R.id.toastView));
TextView txtDate=(TextView)toastView.findViewById(R.id.txtDate);
txtDate.setText("toast appeared at "+Calendar.getInstance().getTime().toLocaleString());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(toastView);
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 specifyinga 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.




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon