Codepath

Displaying the Snackbar

Overview

Snackbars are shown on the bottom of the screen and contain text with an optional single action. They automatically fade out after enough time similar to a toast. Snackbars can be swiped away by the user or contain other actions making them more powerful than simple toasts. However, the API is very familiar.

Note the snackbar at the bottom with an embedded UNDO text on the right side. See this design guide or more details.

Setup

Add to your app/build.gradle:

dependencies {
  implementation "com.google.android.material:material:1.1.0"
}

Simple Snackbar

Create a snackbar using make, setting an optional action and then call .show():

Snackbar.make(parentView, R.string.snackbar_text, Snackbar.LENGTH_LONG)
  .setAction(R.string.snackbar_action, myOnClickListener)
  .show(); // Don’t forget to show!
The first string (R.string.snackbar_text) is shown on the left in the above image, and the second (R.string.snackbar_action) is shown on the right and is clickable.

One difference from using Toasts from Snackbars is that the first parameter parentView requires a View instead of a Context. The snackbar uses this parentView parameter to walk up the parent's hierarchy searching for a CoordinatorLayout, FrameLayout, or the top-most container layout, whichever comes first. Adding a CoordinatorLayout in the view hierarchy is helpful in cases where the floating action button needs to moved to make room for displaying the Snackbar as discussed in this guide.

In a recent update of the support library, you can now specify LENGTH_INDEFINITE that will continue to show the Snackbar until it is dismissed or another one is shown:

Snackbar.make(parentView, R.string.snackbar_text, Snackbar.LENGTH_INDEFINITE).show();

This can be helpful for error messages that should persist on screen until the user performs the action.

Action Click Listener

The setAction method accepts a String resource id and a View.OnClickListener defined and used:

// Define the click listener as a member 
View.OnClickListener myOnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do something here	
    }
});

// Pass in the click listener when displaying the Snackbar
Snackbar.make(parentView, R.string.snackbar_text, Snackbar.LENGTH_LONG)
  .setAction(R.string.snackbar_action, myOnClickListener)
  .show(); // Don’t forget to show!

Configuration Options

Additional options can be used to configure the snackbar such a setActionTextColor and setDuration:

Snackbar.make(parentView, R.string.snackbar_text, Snackbar.LENGTH_LONG)
 .setAction(R.string.snackbar_action, myOnClickListener)  // action text on the right side
 .setActionTextColor(R.color.green)
 .setDuration(3000).show();

That's all!

References

Fork me on GitHub