A toast is a simple popup message which is used to display feedbacks or messages for a short period of time. By default, the toast adjusts its width and height with the amount space required for texts in it. Though we can set the height and width of the message with a custom toast. But as of now, we are going to discuss only the default toast.
android-toast-message-walkytechySyntax:

To display a toast message, we have Toast class in android. In this class, we have a method maketext. This maketext method takes three parameters, the context, the message you want to show and the duration of the message.
At last, we have to display the message with the method called show.

We can also make it in one line:

Now let us understand this with an example.
We have an activity called MainActivity, and we are going to display a toast message in this MainActivty. So our code will be:

Now that you know how to display a toast, we are going to see how to position it. Because by default the toast message always appears at the bottom center of the screen.

So to change the position of the toast message we can use the setGravity method.

Syntax:

As you can see the setGravity method accepts three parameters. The first one is gravity, which is for gravity constant. The second and third one is x-position offset and y-position offset respectively.

Suppose we want to display the toast message at the center of the screen. We can do this:

To display at the top left corner:

To display at the top right corner:

If you increase or decrease the value of the second parameter, which is x, the toast message will move to the right or left respectively.

To move it up or down, increase or decrease the value of the third parameter which is y.

Working with toast message and positioning – Android
Tagged on:

Leave a Reply

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