Create a Snackbar

Introduction
Android has a simple notification system called Snackbar. Snackbars are popups that are anchored to the bottom of the activity and can display short messages as well as have an action button. In this tutorial, you will learn how to create a Snackbar and how to make it be displayed for the user.

Importing
Import the following class:

Creating a Snackbar
Create a new Snackbar by calling the method Snackbar.make.

The first parameter is the view that was used to call the Snackbar, such as an Action Button or a Floating Action Button. The second parameter is the amount of time the Snackbar is supposed to stay visible. It has three options:

After you created the Snackbar, you must call a method to show it. It will stay up for as long as you setted up as the LENGTH parameter.

You don't need to create a new Snackbar everytime you want to display a message. You can create it once and call show everytime you want to display it. That will save the time and memory necessary to allocate a new Object.

By now, your code should look like this:

Setup an Action
Your Snackbar can contain an Action. It can be just an Dismiss button to close the Snackbar, when you choose an INDEFINITE length, or it can perform something else. To setup an Action, call the setAction method before show. The first parameter is the text displayed in the button. The second parameter is a OnClickListener.

If you leave the onClick blank, it will by itself dismiss the snackbar. But you can add any other functions to be executed when the Action is clicked.

When you finish, your code should look like this:

Conclusion
When you finish, your activity should have a working Snackbar that can be called anytime to display a message and also to give the user the option to perform an Action.

You now know how to create a Snackbar, how to set an Action in it and how to display it.