Android toast example

Toast is a simple popup visible for a specific time period. Android toast could be used to show a feedback alert, validation message. message on completion of any operation. etc.

We can show a Toast in an android app through one line of code.

Android toast example

 Toast.makeText(this, "Operation done", Toast.LENGTH_LONG).show();

Syntext: Toast.makeText(context, text, duration).show();

For more understanding below is the example in an activity.

  //Variable (activity) used to store current activity reference.
   Activity activity;
    protected void onCreate(Bundle savedInstanceState) {
        //assign this to activity variable so we can used it in toast
        activity = this;

      Toast.makeText(activity, "Operation done", Toast.LENGTH_LONG).show();

A Toast can be shown for a short time or for a little big time. We need to pass duration in the function. There are two types of duration can be passed in the function. Toast.LENGTH_SHORT shows toast for small time and Toast.LENGTH_LONG shows toast for a little big time.

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × two =