Working with Snackbar in Android

Snackbars are just like Toast messages except they provide action to interact with. Snackbars are displayed at the bottom of the screen and can be swiped off in order to dismiss them.

Simple Snackbar

Below is the syntax of a simple snackbar. The make function accepts three parameters – view, display message and duration of the message to be displayed.

Normally passing CoordinatorLayout as view param is the best option as it allows Snackbar to enable some features like swipe-to-dismiss and automatic moving of widgets like FloatingActionButton.

The duration can be any one among LENGTH_SHORT, LENGTH_LONG and LENGTH_INDEFINITE. When LENGTH_INDEFINITE is used, the snackbar is displayed for indefinite time and can be dismissed with swipe off.

Snackbar snackbar = Snackbar.make(coordinatorLayout, "Welcome to Scorpion_fun_World", Snackbar.LENGTH_LONG);
snackbar.show();

Snackbar with Action Callback

You can also define a callback interaction method using setAction() method. This allows us to take certain action when user interacts with the snackbar.

Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "Message is deleted", Snackbar.LENGTH_LONG)
        .setAction("UNDO", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Message is restored!", Snackbar.LENGTH_SHORT);
                snackbar1.show();
            }
        });

snackbar.show();

Customizing the Snackbar View

Snackbar comes with default white color text and #323232 background color. You can override these colors as shown below.

Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "No internet connection!", Snackbar.LENGTH_LONG)
        .setAction("RETRY", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

// Changing message text color
snackbar.setActionTextColor(Color.RED);

// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();

Here’s how the end result looks.

Snackbar

Software Engineer(Android) at Bennett Coleman and Co. Ltd. (Times Group)

This content has been helpful to you?

Thanks for contributing!

Yes No