Android toasts


Toasts

Toast provides a notification or feedback after a particular operation is complete. For example, after clicking on the scratch card, it might come up as “You Won” or “Better Luck Next time”. It comes up as a popup, and occupies only a certain part of the screen, keeping the primary application visible in the background. We can create custom Toast in Android, which enables us to display a custom message or a text. A good example will be, for an Activity, it can be a text message based on a condition or it can be an image if the condition is false. For creating a custom Toast, a Toast object needs to be created under activity in XML format. A sample code for the same is given below.

Instantiate an Android Toast object

With the makeText() method, which uses the following parameters:

  • The Context of application.
  • The text to display to the user.
  • The period that the toast should stay on the screen.

Using a makeText() method, we return a well initialized Toast object. The class android.widget.Toast is the subclass of java.lang.Object class.

The constants of Toast class

The two constants of the Toast class are mentioned below.

  • public static final int LENGTH_LONG:- It is used to show view for an extended duration of time.
  • public static final int LENGTH_SHORT:- It is used to show the view for a precise duration of time..

The methods of Toast class

The popularly used methods of Toast class are.

  • public static Toast makeText(Context context, CharSequence text, int duration):- This method is used to make the toast containing text and duration.
  • public void show():- It is used to show a toast.
  • public void set margin (float horizontalMargin, float verticalMargin):- It is used to change the horizontal and vertical margin difference.