Toast Function – Android

A Toast is a small pop-up on the screen. It sizes its self allowing it to only use the amount of space which is required to display the text. The user can set the duration of the display.

Creating a Toast the long way:

Some people may find the long way easier to understand and it may be useful if you wanted to create multiple Toasts using the same duration etc, but different text.

First begin by declaring the Context (getting the application), String(declare your text) and (duration) declare how long you want the Toast to show.

An example:

Context context = getApplicationContext();
String message = "Here we go again!";
int duration = Toast.LENGTH_SHORT;

Note: you can also use “Toast.LENGTH_LONG”

The next step is to set the Toast with these preferences and show it. To do so:

Toast toast = Toast.makeText(context, message, duration);;

Another thing you can do with the toast is set it position, where it is going to show. To do so it is fairly simple.

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

This example would position the toast in the top right and corner. You can adjust it to where you want it to display.

Creating a toast the short way:

The short way really is short! Simple do:

Toast.makeText(getApplicationContext(), "The short way really is short!", Toast.LENGTH_SHORT).show();

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s