snackbar
March 2, 2016

Android Material Design Snackbar Tutorial

By admin


One of the basic UX component in Android is an Toast. It is generally used to show little message to the user. But last year when material design was released, a new UX component Snackbar was introduced. Android Snackbar is just like a Toast message except that it has an option for user feedback. You can call it as a toast message with an action button.

What is Snackbar ?

A Snackbar is a lightweight material design method for providing feedback to a user, while optionally providing an action to the user. They are displayed on the screen until a specified interval has passed, the user swipes to dismiss them, or when the user interacts with another part of the screen. Snackbar is the best replacement for toast messages & you can set actions in the form of pop up.

Let’s Get it Working

In this tutorial we are going to learn how to use Snackbar. To really understand the usage of Snackbar we will create an app . The App contains simple buttons which will demonstrate the different usages of Snackbar.

DownloadCode
 
github

Step 1 ) Update build.gradle file .

Before you can use Snackbar in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project .

dependencies {
    ...
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

Step 2) Update strings.xml .

Add the below string values to the string.xml located in res => values => strings.xml .

<resources>
    <string name="app_name">SnackBar</string>
    <string name="action_settings">Settings</string>
    <string name="text_simple_snackbar">Simple Snackbar</string>
    <string name="text_custom_snackbar">Snackbar Custom Color</string>
    <string name="text_multicolor_snackbar">Snackbar MultiText Color</string>
    <string name="text_snackbar_action">Snackbar with Action Callback</string>
</resources>

Step 3) Update activity_main.xml .

Open the layout file for the MainActivity.java i.e activity_main.xml and add the below code in your layout file . The code will create 4 buttons .

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/coordinatorLayout"
    tools:context="com.androidtutorialshub.snackbar.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/buttonSimpleSnackbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_simple_snackbar" />

        <Button
            android:id="@+id/buttonCustomSnackbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_custom_snackbar" />

        <Button
            android:id="@+id/buttonMultiColorSnackbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_multicolor_snackbar" />

        <Button
            android:id="@+id/buttonActionCallbackSnackbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_snackbar_action" />
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

Step 4) Main Activity Class.

Now Open MainActivity.java and make some changes in code . Here I created objects for the coordinator layout and buttons . Also Created OnClickListener for the buttons .

package com.androidtutorialshub.snackbar;

import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;

    // Button variables
    private Button buttonSimpleSnackbar;
    private Button buttonCustomSnackbar;
    private Button buttonMultiColorSnackbar;
    private Button buttonActionCallbackSnackbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViews();
        initListeners();

    }

    /**
     * method to initialize views objects
     */
    private void initViews() {
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        buttonSimpleSnackbar = (Button) findViewById(R.id.buttonSimpleSnackbar);
        buttonCustomSnackbar = (Button) findViewById(R.id.buttonCustomSnackbar);
        buttonMultiColorSnackbar = (Button) findViewById(R.id.buttonMultiColorSnackbar);
        buttonActionCallbackSnackbar = (Button) findViewById(R.id.buttonActionCallbackSnackbar);

    }

    /**
     * method to initialize listeners
     */
    private void initListeners() {

        buttonSimpleSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              
            }
        });

        buttonCustomSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });

        buttonMultiColorSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {         

            }
        });

        buttonActionCallbackSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               
            }
        });
    }


}

Snackbar Screen with Buttons

Snackbar Screen with Buttons






Step 5) Update Actions in Button onClick().

-> Simple Snackbar

Below is the code to display 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. And the duration can be LENGTH_SHORT, LENGTH_LONG or LENGTH_INDEFINITE. When LENGTH_INDEFINITE is used, the Snackbar will be displayed indefinite time and can be dismissed with swipe off.
Add the below code inside the buttonSimpleSnackbar onClick().

 Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Android Tutorials Hub Welcomes You", Snackbar.LENGTH_LONG);

         snackbar.show();
Simple Snackbar

Simple Snackbar

-> Custom Text Color Snackbar

Snackbar comes with default white color text and blackish background color. You can change these colors according to your requirements. I changed the text color to red and action text color to white.
Add the below code inside the buttonCustomSnackbar onClick().

Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Server Not Responding!", Snackbar.LENGTH_LONG)
                        .setAction("TRY AGAIN", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        });

// Message text color
snackbar.setActionTextColor(Color.WHITE);

// Action button text color
View snackBarView = snackbar.getView();
TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);

snackbar.show();
Custom Text Color Snackbar

Custom Text Color Snackbar

-> Multi Color Text Snackbar

Some times you need the multi color text in Snackbar. Here I use SpannableStringBuilder to create multi color text .
Add the below code inside the buttonMultiColorSnackbar onClick().

// Creating MultiColor Text
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Welcome to ");
int boldStart = snackbarText.length();
snackbarText.append("Android Tutorials Hub");
snackbarText.setSpan(new ForegroundColorSpan(Color.CYAN), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                snackbarText.append(".");

Snackbar snackbar = Snackbar
                   .make(coordinatorLayout, snackbarText, Snackbar.LENGTH_LONG);

snackbar.show();
Multi Color Text Snackbar

Multi Color Text Snackbar

-> Snackbar with Action Callback

You can also mention a callback method using setAction() method. This allows you to take some action when user interacts with the snackbar.
Add the below code inside the buttonActionCallbackSnackbar onClick().

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

                snackbar.show();
Snackbar with Action Callback

Snackbar with Action Callback

Snackbar for Action Callback

Snackbar for Action Callback

Complete Main Activity Class.

package com.androidtutorialshub.snackbar;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;

    // Button variables
    private Button buttonSimpleSnackbar;
    private Button buttonCustomSnackbar;
    private Button buttonMultiColorSnackbar;
    private Button buttonActionCallbackSnackbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViews();
        initListeners();

    }

    /**
     * method to initialize views objects
     */
    private void initViews() {
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        buttonSimpleSnackbar = (Button) findViewById(R.id.buttonSimpleSnackbar);
        buttonCustomSnackbar = (Button) findViewById(R.id.buttonCustomSnackbar);
        buttonMultiColorSnackbar = (Button) findViewById(R.id.buttonMultiColorSnackbar);
        buttonActionCallbackSnackbar = (Button) findViewById(R.id.buttonActionCallbackSnackbar);

    }

    /**
     * method to initialize listeners
     */
    private void initListeners() {

        buttonSimpleSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Android Tutorials Hub Welcomes You", Snackbar.LENGTH_LONG);

                snackbar.show();
            }
        });

        buttonCustomSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Server Not Responding!", Snackbar.LENGTH_LONG)
                        .setAction("TRY AGAIN", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        });

                // Message text color
                snackbar.setActionTextColor(Color.WHITE);

                // Action button text color
                View snackBarView = snackbar.getView();
                TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.RED);

                snackbar.show();
            }
        });

        buttonMultiColorSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Creating MultiColor Text
                SpannableStringBuilder snackbarText = new SpannableStringBuilder();
                snackbarText.append("Welcome to ");
                int boldStart = snackbarText.length();
                snackbarText.append("Android Tutorials Hub");
                snackbarText.setSpan(new ForegroundColorSpan(Color.CYAN), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                snackbarText.append(".");

                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, snackbarText, Snackbar.LENGTH_LONG);

                snackbar.show();


            }
        });

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

                snackbar.show();
            }
        });
    }
}
DownloadCode
 
github

Enjoy Coding and Share Knowledge