Pages

Friday, April 29, 2016

Android popup messages using Toast

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
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.

Related Posts by Categories

android
Android App

0 comments:

Post a Comment