mydomain
No ADS
No ADS

Android Toast Tutorial with Examples

  1. Android Toast
  2. Custom Toast
  3. Android Snackbar

1. Android Toast

No ADS
Android Toast is a small message that the application sends to the user. It pops up close to the bottom of the screen (by default) and automatically disappears after the timeout.
A simple syntax is:
Toast toast = Toast.makeText(context, "message", duration);
toast.show();
context
Application context
message
The message content will be displayed.
duration
It accepts either Toast.LENGTH_LONG ( 1 ) or Toast.LENGTH_SHORT ( 0 ),
  • duration = Toast.LENGTH_LONG meaning Toast will be displayed for a long period of time, namely 3.5 seconds.
  • duration = Toast.LENGTH_SHORT meaning Toast will be displayed for a short period of time, namely 2 seconds.
For example:
Toast.makeText(MainActivity.this, "Data has been saved successfully!", Toast.LENGTH_LONG).show();
Toast Position
By default Toast will be displayed close to the bottom of the screen and horizontally centered. By using the setGravity() method, you can change its display position.
private void showOnLeftTop()  {
    Toast toast =  Toast.makeText(MainActivity.this, "This is a message!", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.LEFT | Gravity.TOP, 20, 30);
    toast.show();
}

private void showOnTopRight()  {
    Toast toast =  Toast.makeText(MainActivity.this, "This is a message!", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.TOP | Gravity.RIGHT, 20, 30);
    toast.show();
}

private void showOnTopCenter()  {
    Toast toast =  Toast.makeText(MainActivity.this, "This is a message!", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.TOP | Gravity.CENTER, 20, 30);
    toast.show();
}

private void showOnCenter()  {
    Toast toast =  Toast.makeText(MainActivity.this, "This is a message!", Toast.LENGTH_SHORT);
    // Gravity.CENTER = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;
    toast.setGravity(Gravity.CENTER, 20, 30);
    toast.show();
}

2. Custom Toast

No ADS
Basically, Toast is easy for you to use and good enough to give a notification to the user. However, if you expect a more sophisticated interface, you can customize your Toast by using the setView() method.

3. Android Snackbar

No ADS
Snackbar is a small interface component that provides a brief response after the user's action. it appears at the bottom of the screen, and automatically disappears after the timeout or when the user interacts on a different place on the screen. Additionally, Snackbar provides an option button to perform an action. For example, undo an action that has just been performed or retry the action in case it fails.
Snackbar is pretty similar to the Toast that you might be interested:
No ADS

Android Programming Tutorials

Show More
No ADS