Playing with Android Toast and Snackbar

Shashank Mohabia
3 min readMay 27, 2020

--

We use Toast and Snackbar in our android applications a lot. These help us to display temporary information for the users or information which has short term importance like success messages or error alerts. In this blog, I covered all the magic we can do using these components. Let’s begin.

Toast:

A simple toast can be displayed using the following code:

Toast.makeText(context, text, duration).show()

This gives a grey colored toast at the bottom of your screen for a small period of time. Now you might think what else to expect from a toast but there are ways to customize it. Let’s look at two of them:

Positioning your Toast:

We can change the position of toast by setting its gravity like this:

setGravity(gravity_value, x_offset, y_offset)For example:Toast.makeText(context, text, Toast.LENGTH_SHORT).apply {
setGravity(Gravity.CENTER, 0, 0)
show()
}

These gravity values can be accessed from Gravity class. You can set multiple gravities like for setting the toast’s position Top-left use

setGravity(Gravity.TOP or Gravity.LEFT, x_offset, y_offset)

Custom Toast View:

If you don’t like the default view of toast you can create your own view for toast. For this just create a custom_toast layout and inflate it using layout inflator.

Create a custom_layout.xml like this or whatever way you want to design it. Use id for the root view like I used custom_toast_container here:

Then use layoutInflator to inflate this layout and set it to the view of toast:

Now you can have those colorful toasts that you wish for🤩

Note: Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast.

Snackbar:

The snackbar widget provides brief feedback about an operation through a message at the bottom of the screen. Snackbars disappear automatically, either after a timeout or after a user interaction elsewhere on the screen, and can also be swiped off the screen.

Snackbars can also offer the ability to perform an action, such as undoing an action that was just taken or retrying an action that had failed.

Note: previously snackbar was a part of the support library but as that is deprecated now you should use the google material snackbar.

Creating a basic snackbar is as simple as creating a Toast and has a very similar syntax:

Snackbar.make(View, text, duration)

For example:

You can also add actions to your snackbars and then can attach on click listeners on it. Also, you can set the action text’s color otherwise it will use your theme’s primary color. So a complete snackbar can look like this:

Feel free to comment if there are doubts or if you feel anything needs to be corrected😀.

References:

Toast Documentation

Snackbar Documentation

--

--