Posts Tagged Positioning the Toast

Toast Notification in Android with a simple example

A Toast Notification is just a pop up message to notify the user of some event. It just remains on the screen for some time and fades away. The user can’t interact with the toast message, that is, it doesn’t receive any user response and we can still interact with our activity when it’s still on the screen.

Let’s see how a Toast Notification can be created.

First of all, create an instance of the Toast object as shown below:

Toast toast=Toast.makeText(getApplicationContext(), "This is a Toast",Toast.LENGTH_LONG );

Here, the makeText() has got three parameters:

1)Context – the Application context

2)Text – the Text Message that needs to be displayed(here its “This is a Toast”)

3)Duration – the duration for the Toast to be displayed

Thus, the object ‘toast’ has got the details for a simple Toast.

Now, We need to display the Toast and for that we need a method named show().

The code for display is simple:;

We can also position the Toast as we desire using a method named setGravity() which has got three parameters:-gravity,x-offset,y-offset.

For example:

toast.setGravity(Gravity.TOP, 40, 30);

Note: By default the Toast appears at the bottom, centred horizontally. So if no need of setGravity() method if you don’t want to position the Toast.

The Whole code is given below:

package com.deepthi.mytoast;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MyToastDemo extends Activity {
    /** Called when the activity is first created. */
                Button toastbtn1;
    public void onCreate(Bundle savedInstanceState) {
        toastbtn1.setOnClickListener(new OnClickListener() {
                                                public void onClick(View v) {
                                                                // TODO Auto-generated method stub
                                                                Toast toast=Toast.makeText(getApplicationContext(), "This is a Toast",Toast.LENGTH_LONG );
                                                                toast.setGravity(Gravity.TOP, 40, 30);

The XML Layout:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:text="@string/hello" />
        android:text="Toast" />

The Output looks like this:


, , , , , , , , ,