Snackbar in Android: Tutorial

Snackbars are used to display a message at the bottom of the screen, whenever an action is performed. It is one of the UX features introduced as part of Material Design. Snackbars have the following features:

  • Only one snackbar may be displayed at a time.
  • They may contain a text action, but no icons.
  • Unlike Toast messages, snackbar can be swiped off-screen.

In this tutorial, we will see the implementation of snackbar. In the end of this tutorial, you will be learning on :

  • how to display a simple snackbar.
  • how to add action text to snackbar.
  • how to customize the color of the text displayed in the snackbar.

Simple Snackbar

You can display a snackbar using the following code:

Here view is the reference to the view or layout in which you wish to display the Snackbar. The second argument is the message to be displayed in the snackbar and duration of display of message can be given as the third argument. Duration can be either Snackbar.LENGTH_SHORT, Snackbar.LENGTH_LONG or Snackbar.LENGTH_INDEFINITE. Like Toast messages, we call show() method to display the Snackbar.

Simple Snackbar 1024x561 - Snackbar in Android: Tutorial

Snackbar with Action Button

We can make use of setAction callback to set an action for the Snackbar. Here I have added an undo link, on click of which another snackbar will be displayed.

Snackbar with Action

Snackbar with Customized Colors

To change the color of the action text, call setActionTextColor callback and in order to change the color of the text, you need to get the View of the snackbar, retrieve the TextView from the View and then set the color to the TextView as shown above.

Snackbar with Custom Colors

Creating a new Project

1. In Android Studio create a new project with the name Snackbar Demo. While creating the project choose Basic Activity from the list of activities.

Snackbar Creating project

2. Add necessary strings to strings.xml:

3. Edit content_main.xml to the following. I have added 3 buttons to demonstrate different types of Snackbars.

4. Open MainActivy.java and add the following code:

Now run the application on your device or emulator.

Snackbar Tutorial Demo

Download Source CodeDownload APK

If you have any doubts, then we can discuss them in the comments section. If you have liked this tutorial, please do follow us on Twitter and Facebook.

Stay Connected

No spam guarantee.

Abhishek

Abhishek

Abhishek loves coding. His favorite is Android Development. Apart from coding he loves traveling and reading.
Abhishek

Leave a Reply

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