Thursday, March 26, 2015

How to use Toast in Android

1. Android Toast Introduction

In Android, Toast is a view that contains a little message for app user. Toast provide simple feedback about an operation. Toast display in user interface as a popup but the current Activity remain visible and interactive. Toast only fill the amount of space required to display the message.

Android developers generate a Toast on an app interface when they want to display a quick feed for user, such as when user leave an Activity without saving it, then a Toast can say your work is saved automatically. App user's does not need to close the Toast popup, it will automatically disappear after timeout. Toast can not catch user response as Notification.

Toast appear as a floating view over application and it never receive focus, so user can do nothing with Toast message instead read it.

Toast Constructor
Toast(Context context) allow us construct an empty Toast object. We can import a Toast class in our application java file as android.widget.Toast. After initializing an empty Toast object, we can populate with massage, specify duration and display it app interface.

We also can instantiate a Toast object using makeText() method. The makeText(Context context, int resId, int duration) method has three required parameters.



The context parameter specify the Context to use, usally this is Application or Activity object. We can simply pass the getApplicationContext() method as this parameter. getApplicationContext() return the context of the single, global Application object of the current process.

makeText() method's resId parameter specify the resource id of the string resource to use. It can be formatted text. Simply we can pass a string as this parameter value such as "this is a toast message".

makeText() method's duration parameter specify how long to display the message. There are two options available for this parameter value, those are LENGTH_SHORT and LENGTH_LONG. The LENGTH_SHORT display the view or text notification for a short period of time, this is default and the LENGTH_LONG show the Toast for long period of time.

Finally, show() method show the Toast message for the specified duration.

2. Display Toast On Specific Position

If you do not change the default Toast Gravity, the Toast display near the bottom of app user interface and also centered horizontally. We can change the default Toast message display location by using setGravity() method. Gravity is a standard constants and tools for placing an object within a potentially larger container.

setGravity() method set the location at which the notification should appear on the screen. setGravity(int gravity, int xOffset, int yOffset) has three required parameters. First parameter is a Gravity constant, second parameter define the x offset and last parameter define the y offset.

Gravity parameter allow us to specify the exact location to display the Toast view such as if we want to place the Toast on screen center then we can pass this parameter value as Gravity.CENTER, we also should pass zero (0) for both x offset and y offset values to place it exact center.

Another example, if we want to show the Toast on app screen top right position then we need to pass the Gravity parameter value as Gravity.TOP|Gravity.RIGHT.

xOffset parameter allow us to nudge the Toast position to the right by increasing the value. If we want to nudge the Toast position to down then we can increase the yOffset parameter value as required.

Finally, if we want to display a Toast message on app interface center and 50 xOffset and 25 yOffset then we can pass parameters to the method as setGravity(Gravity.CENTER,50,25).



Gravity BOTTOM push object to the bottom of its container. Gravity CENTER show the object in the center of container both horizontal and vertical axis. Gravity CENTER_HORIZONTAL place object at the horizontal center of its container. Gravity CENTER_VERTICAL place object in the vertical center of its container without changing its size. Gravity LEFT display object to the left of its container. Gravity RIGHT display object to the right of its container layout. Gravity TOP put the specified object at the top of its container (parent layout).

3. Toast class others important public methods

cancel() method close the Toast view if it is showing; otherwise don't show if it is not showing yet. getDuration() method allow us to get the Toast duration. getGravity() method get the location at which the Toast notification should appear on the app screen. setGravity() method set the location at which the Toast should appear in app interface.

getHorizontalMargin() and getVerticalMagin() return the horizontal and vertical margin. setMargin() method set the margins of the view. getView() method return the Toast view. setView() method set the view to show as Toast notification. getXOffset() and getYOffset() method() return X offset and Y offset in pixels to apply to the Gravity's location.

makeText(Context context, CharSequence text, int duration) method allow us to display a standard Toast that just contains a text view.

setText(int resId) method allow us to update the text in a Toast that was previously created using one of the makeText() methods. setText(CharSequence s) overloaded method also update the text in a Toast that was previously created using one of the makeText() methods. Finally, show() method show the Toast view for the specified duration. Those helpful methods allow us to display a custom Toast in an Android application.

4. Toast Example

activity_android_toast_example.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="com.cfsuman.me.myapplication5.AndroidToastExample"
    >
    <Button
        android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Default Position"
        android:onClick="button1_action"
        />
    <Button
        android:id="@+id/button2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Top Left + Length Long"
        android:onClick="button2_action"
        android:layout_below="@id/button1"
        />
    <Button
        android:id="@+id/button3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Top Right"
        android:onClick="button3_action"
        android:layout_below="@id/button2"
        />
    <Button
        android:id="@+id/button4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Bottom Left"
        android:onClick="button4_action"
        android:layout_below="@id/button3"
        />
    <Button
        android:id="@+id/button5"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Bottom Right"
        android:onClick="button5_action"
        android:layout_below="@id/button4"
        />
    <Button
        android:id="@+id/button6"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Center"
        android:onClick="button6_action"
        android:layout_below="@id/button5"
        />
    <Button
        android:id="@+id/button7"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Top + Center Horizontal"
        android:onClick="button7_action"
        android:layout_below="@id/button6"
        />
    <Button
        android:id="@+id/button8"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Left + Center Vertical"
        android:onClick="button8_action"
        android:layout_below="@id/button7"
        />
    <Button
        android:id="@+id/button9"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Center + X=225"
        android:onClick="button9_action"
        android:layout_below="@id/button8"
        />
    <Button
        android:id="@+id/button10"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Center + Y=225"
        android:onClick="button10_action"
        android:layout_below="@id/button9"
        />
    <Button
        android:id="@+id/button11"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Toast: Center + Y=225+ X=225"
        android:onClick="button11_action"
        android:layout_below="@id/button10"
        />
</RelativeLayout>
AndroidToastExample.java

package com.cfsuman.me.myapplication5;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//additional imported classes
import android.view.View;
import android.widget.Toast;
import android.view.Gravity;


public class AndroidToastExample extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_toast_example);
    }

    public void button1_action(View v){
        //display a toast notification on default position and short length/duration
        Toast toast_button1 = Toast.makeText(getApplicationContext(),"Toast Default Position",Toast.LENGTH_SHORT);
        toast_button1.show();
    }
    public void button2_action(View v){
        //display a toast notification ofor long length/duration
        Toast toast_button2 = Toast.makeText(getApplicationContext(),"Toast Top Left",Toast.LENGTH_LONG);
        //specify the toast display position exact top left corner. no x or y offset
        toast_button2.setGravity(Gravity.TOP|Gravity.LEFT,0,0);
        toast_button2.show();
    }
    public void button3_action(View v){
        Toast toast_button3 = Toast.makeText(getApplicationContext(),"Toast Top Right",Toast.LENGTH_SHORT);
        //specify the toast display position exact top right corner. no x or y offset
        toast_button3.setGravity(Gravity.TOP|Gravity.RIGHT,0,0);
        toast_button3.show();
    }
    public void button4_action(View v){
        Toast toast_button4 = Toast.makeText(getApplicationContext(),"Toast Bottom Left",Toast.LENGTH_SHORT);
        //specify the toast display position exact bottom left corner. no x or y offset
        toast_button4.setGravity(Gravity.BOTTOM|Gravity.LEFT,0,0);
        toast_button4.show();
    }
    public void button5_action(View v){
        Toast toast_button5 = Toast.makeText(getApplicationContext(),"Toast Bottom Right",Toast.LENGTH_SHORT);
        //specify the toast display position exact bottom right corner. no x or y offset
        toast_button5.setGravity(Gravity.BOTTOM|Gravity.RIGHT,0,0);
        toast_button5.show();
    }
    public void button6_action(View v){
        Toast toast_button6 = Toast.makeText(getApplicationContext(),"Toast Center",Toast.LENGTH_SHORT);
        //specify the toast display position exact parent layout center. no x or y offset
        toast_button6.setGravity(Gravity.CENTER,0,0);
        toast_button6.show();
    }
    public void button7_action(View v){
        Toast toast_button7 = Toast.makeText(getApplicationContext(),"Toast Top + Center Horizontal",Toast.LENGTH_SHORT);
        //specify the toast display position exact parent layout top center horizontal. no x or y offset
        toast_button7.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL,0,0);
        toast_button7.show();
    }
    public void button8_action(View v){
        Toast toast_button8 = Toast.makeText(getApplicationContext(),"Toast Left + Center Vertical",Toast.LENGTH_SHORT);
        //specify the toast display position exact parent layout left center vertical. no x or y offset
        toast_button8.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL,0,0);
        toast_button8.show();
    }
    public void button9_action(View v){
        Toast toast_button9 = Toast.makeText(getApplicationContext(),"Toast Center + x=225",Toast.LENGTH_SHORT);
        //specify the toast display position parent layout center. x position offset 225 and no y offset
        toast_button9.setGravity(Gravity.CENTER_VERTICAL,225,0);
        toast_button9.show();
    }
    public void button10_action(View v){
        Toast toast_button10 = Toast.makeText(getApplicationContext(),"Toast Center + y=225",Toast.LENGTH_SHORT);
        //specify the toast display position parent layout center. no x offset and y position offset 25
        toast_button10.setGravity(Gravity.CENTER_VERTICAL,0,225);
        toast_button10.show();
    }
    public void button11_action(View v){
        Toast toast_button11 = Toast.makeText(getApplicationContext(),"Toast Center + x=225 + y=225",Toast.LENGTH_SHORT);
        //specify the toast display position parent layout center. x position offset 225 and y position offset 225
        toast_button11.setGravity(Gravity.CENTER_VERTICAL,225,225);
        toast_button11.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

5. Create and display a custom Toast View (colored background and border)

Android app developers can create a custom Toast View and display it to user interface. To show a custom Toast notification view, at first we need to create a custom layout XML file to put elements in it to display on custom Toast View. We must put the layout XML file into res/layout folder.

We also need to write an id for layout root element such as if we put a RelativeLayout as our custom layout file's root object then we need to declare 'android:id attribute' with values for this RelativeLayout element. Next, we need to pass the root view object (such as RelativeLayout) to LayoutInflater inflate() method to specify it as a custom Toast view.

LayoutInflater class getLayoutInflater() and inflate() method help us to define a view as custom Toast View. Next, we can initialize an empty Toast object by using Toast(Context context) constructor. we can define the newly initilized empty Toast object's duration, Gravity and text by using setDuration() , setGravity() and setText() methods. setView() method set the specified view object as custom Toast view. At last, we can call the show() method to display this custom Toast view to app user interface.

LayoutInflater class instantiate a layout XML file into its corresponding View objects. we can use it by calling getLayoutInflater() method to retrieve a standard LayoutInflater instance that is already hooked up to the current context. getLayoutInflater() method allow us to quick access to the LayoutInflater instance that this window retrieve from this context.

LayoutInflater class inflate(int resource, ViewGoup root) method allow us to inflate a new view hierarchy from the specified XML resource.
activity_custom_toast_example.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.cfsuman.me.myapplication5.CustomToastExample"
    >
    <Button
        android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Show Custom Toast View"
        android:onClick="perform_action"
        />
</RelativeLayout>
CustomToastExample.java

package com.cfsuman.me.myapplication5;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//additional imported classes
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Gravity;

import android.widget.TextView;
import android.widget.Toast;

public class CustomToastExample extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_toast_example);
    }

    public void perform_action(View v){
        LayoutInflater inflater = getLayoutInflater();
        //specify the layout xml file which we want to use as a custom toast view
        //specify the actual layout root element which we want to display as custom toast view
        View toastLayout = inflater.inflate(R.layout.activity_custom_toast_view_layout,
                (ViewGroup) findViewById(R.id.custom_toast_view_layout_root));

        //Initialize custom toast view toast notification textview
        TextView tv_toast_message = (TextView) toastLayout.findViewById(R.id.tv_toast_message);
        //Set the toast message
        tv_toast_message.setText("Custom Toast Notification....");

        //Initialize a new Toast notification
        Toast customToastView = new Toast(getApplicationContext());
        //Set the toast display position
        customToastView.setGravity(Gravity.CENTER,0,50);
        //Set the Toast display duration/length to long
        customToastView.setDuration(Toast.LENGTH_LONG);
        //Specify the custom layout as toast's layout
        customToastView.setView(toastLayout);
        //Display the custom toast in app user interface
        customToastView.show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
activity_custom_toast_view_layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_view_layout_root"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:padding="15dp"
    android:background="@drawable/custom_toast_view_background"
    >
    <TextView
        android:id="@+id/tv_toast_title"
        android:text="Toast Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2F4F4F"
        android:textColor="#ffffff"
        android:layout_marginBottom="15dp"
        android:padding="5dp"
        android:textSize="20dp"
        />
    <ImageView
        android:id="@+id/android_image"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/androidimage"
        android:layout_below="@id/tv_toast_title"
        android:layout_marginRight="10dp"
        />
    <TextView
        android:id="@+id/tv_toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_toast_title"
        android:layout_toRightOf="@id/android_image"
        android:layout_alignBaseline="@id/android_image"
        android:textSize="25dp"
        />
</RelativeLayout>
res/drawable/custom_toast_view_background.xml

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#BDB76B"/>
            <stroke android:color="#556B2F" android:width="2dp"/>
            <corners android:bottomRightRadius="25dp"/>
        </shape>
    </item>
</selector>

More android examples