Basics of Toast Notification in Android

Introduction

People presently use Android-enabled smartphones. So in these phones when a small message, more precisely called a small notification, appears on the screen for some time and then vanishes then that is called a toast.

It only requires the amount of space required for the message and the current activity remains visible and is interactive with the user. For example, when internet browsing, in the history part, we can see the various links we have visited. Now a bookmarked one raises a popup "bookmarked saved" that means the toast tells the user that he may continue. Toasts automatically disappear after a period of time because there is a time set for its visibility on any activity.

                                       

      Figure: The red portion illustrates the Toast "Added to Bookmarks"

Toast class

A toast class is a view containing a small message for the user as stated previously. When the view is shown to the user it  appears as a floating view over the application. It will never receive focus means it can't be interactable. The user will probably be in the middle of typing something else so these toast notifications just provide notification and does not hinder the work of the user. Examples are the volume control and the brief message saying that your settings have been saved and draft saved and so on.

The most convieninet way to use and call the static member is to use the toast class and access these static members within a program.

Note: users can't interact with these toast notifications, these are just for information in response to user inputs generally.

First create a toast object with one of the makeTest() methods. This method takes the three parameters "application context" , "the text message" and "duration of toast". It will return a properly initialized toast object. To display a toast message we can use any method.

  1. Context context = getApplicationContext();  
  2. CharSequence text = "Welcome Gaurav!!";  
  3. int duration = Toast.LENGTH_SHORT;  
  4.   
  5. Toast toast = Toast.makeText(context, text, duration);  
  6. toast.show();  

However we have created a toast method that will initiate the toast. We have already defined all the toast attributes, like length, duration and many things to be defined.

Chaining of members is possible. Mainly methods prevent the holding of a toast object.

  1. Toast.makeText(context, text, duration).show();  
Positioning Your toast

A standard toast notification must appear near the bottom of the screen and must be centered horizontally as well. However we can see these things in any version of Android and other phones as well. You can change this position with the setGravity(int, int, int) method. This accepts the three parameters, a Gravity constant, an x-position offset and a y-position offset. This is quite interesting that we use this method.

For example if you want that my text should appear in the top-left corner you can set the gravity as shown below.
  1. toast.setGravity(Gravity.TOP|Gravity.LEFT, 00);  
If we want that the position should be right then we must increase the value of the second parameter and if we want the toast to appear down then increase the value of the third and last parameter. However it depends upon us, wherever we want the toast on screen.

Creating the custom Toast view

Now to print the Toast directly we need to add a TextView as we have created in previous articles. Now if we don't create a custom text view then it will look weird so it is the duty of the programmer to make a system with a look and feel.

Define the layout in the activity_main.xml and use the following procedure:
  • Change the RelativeLayout with LinearLayout.
  • Insert ImageView.      
  1. <ImageView android:src="@drawable/droid"  
  2.              android:layout_width="wrap_content"  
  3.              android:layout_height="wrap_content"  
  4.              android:layout_marginRight="8dp"  />  
Create the TextView 
  1. <TextView android:id="@+id/text"  
  2.            android:layout_width="wrap_content"  
  3.            android:layout_height="wrap_content"  
  4.            android:textColor="#FFF"  
  5.   />  
Now follow the code given below so this creates some text view on the activity.
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.    android:id="@+id/toast_layout_root"  
  3.    android:orientation="horizontal"  
  4.    android:layout_width="fill_parent"  
  5.    android:layout_height="fill_parent"  
  6.    android:padding="8dp"  
  7.    android:background="#DAAA">
  8.   
  9.    <ImageView android:src="@drawable/droid"  
  10.       android:layout_width="wrap_content"  
  11.       android:layout_height="wrap_content"  
  12.       android:layout_marginRight="8dp"  />
  13.   
  14.    <TextView android:id="@+id/text"  
  15.       android:layout_width="wrap_content"  
  16.       android:layout_height="wrap_content"  
  17.       android:textColor="#FFF"  />
  18.   
  19. </LinearLayout>  
Here we have defined ImageView and Textview as well. Now add the corresponding Java code.
  1. package com.example.gkumar.Toast;  
  2. import android.R;  
  3. import android.support.v7.app.ActionBarActivity;  
  4. import android.os.Bundle;  
  5. import android.view.Menu;  
  6. import android.view.MenuItem;  
  7.   
  8.   
  9. public class MainActivity extends ActionBarActivity {  
  10.   
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_list_item);  
  15.     }  
  16.     public boolean onCreateOptionsMenu(Menu menu) {  
  17.             
  18.   
  19.         LayoutInflater inflater = getLayoutInflater();  
  20.         View layout = inflater.inflate(R.layout.custom_toast,  
  21.                                (ViewGroup) findViewById(R.id.main_layout_root));  
  22.   
  23.         TextView text = (TextView) layout.findViewById(R.id.text);  
  24.         text.setText("welcome Gaurav");  
  25.   
  26.     Toast toast = new Toast(getApplicationContext());  
  27.     toast.setGravity(Gravity.CENTER_VERTICAL, 00);  
  28.     toast.setDuration(Toast.LENGTH_LONG);  
  29.     toast.setView(layout);  
  30.     toast.show();  
  31.     }  
  32.     @Override  
  33.     public boolean onOptionsItemSelected(MenuItem item) {  
  34.         // Handle action bar item clicks here. The action bar will  
  35.         // automatically handle clicks on the Home/Up button, so long  
  36.         // as you specify a parent activity in AndroidManifest.xml.  
  37.         int id = item.getItemId();  
  38.         if (id == R.id.action_settings) {  
  39.             return true;  
  40.         }  
  41.         return super.onOptionsItemSelected(item);  
  42.     }  
  43. }  
Here basically what is happening is that first, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. Now it can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements.

Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and it the inflated layout. You can now display the toast with your custom layout by calling show().

Note: Here we are not using any public constructor for a toast because we haven't used setView(view) here. If anyone doesn't want to use a custom layout then use the makeText.() method to create the toast.

Summary

This article explains the basics of Toasts and how it can be created. It may be considered to be like notifications but it is quite snazzy and looks awesome and renders for just a second and then vanishes. 

Up Next
    Ebook Download
    View all
    Learn
    View all