Another interesting component introduced in Material Design is the Snackbar. Snackbars are just like Toast messages except they provide action to interact with. Snackbar will be displayed at the bottom of the screen and can be swiped off in order to dismiss them.

This article explains about snackbar with few examples covering different scenarios.

android-material-design-snackbar-tutorial

1. 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 automatically moving of widgets like FloatingActionButton.

And the duration should 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.

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

snackbar.show();
android-snackbar-example

2. Snackbar with Action Callback

You can also mention 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();
android-snackbar-with-action-callback-undo

3. Customizing the Snackbar View

Snackbar comes with default white color text and #323232 background color. You can override these colors as mentioned 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();
android-snackbar-custom-color-view-text-color

4. Creating New Project

Now we’ll create a simple app to sea the snackbar in action when the app is having a CoordinatorLayout and a FloatingActionButton.

1. In Android Studio, go to File β‡’ New Project and fill all the details required to create a new project.

2. Open build.gradle and add design support library dependency.

com.android.support:design:23.0.1

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}

3. Optionally you can apply the material design theme by following the steps mentioned here.

4. Open the layout file your main activity activity_main.xml and below code. Here you can see I have added the CoordinatorLayout and FloatingActionButton.

<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:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/btnSimpleSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Simple Snackbar" />

        <Button
            android:id="@+id/btnActionCallback"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="With Action Callback" />

        <Button
            android:id="@+id/btnCustomSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Custom Color" />

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_dialog_email" />

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

5. Now open MainActivity.java and make the changes as mentioned below. This activity contains three button click listeners to show the different ways of implementing the snackbar covering the scenarios explained above.

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private CoordinatorLayout coordinatorLayout;
    private Button btnSimpleSnackbar, btnActionCallback, btnCustomView;
    private FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
                .coordinatorLayout);

        fab = (FloatingActionButton) findViewById(R.id.fab);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);

        btnSimpleSnackbar = (Button) findViewById(R.id.btnSimpleSnackbar);
        btnActionCallback = (Button) findViewById(R.id.btnActionCallback);
        btnCustomView = (Button) findViewById(R.id.btnCustomSnackbar);

        btnSimpleSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Welcome to AndroidHive", Snackbar.LENGTH_LONG);

                snackbar.show();
            }
        });

        btnActionCallback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                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();
            }
        });

        btnCustomView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                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();
            }
        });
    }
}

Run and test the app.

android-material-design-snackbar-example
Subscribe
Notify of
guest
81 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nirav Jain
Nirav Jain
5 years ago

anyway to call snackbar without triggering it…. like a welcome message when someone opens the app

Ravi Tamada
5 years ago
Reply to  Nirav Jain

You can keep this code in onCreate() method.

Snackbar snackbar = Snackbar
.make(coordinatorLayout, “Welcome to AndroidHive”, Snackbar.LENGTH_LONG);

snackbar.show();

Renitto Jose
Renitto Jose
5 years ago

tried it nice one but the problem is can’t set width of snackbar to fill parent on large devices(7″ and 10″ tablets etc) .it works fine on phones. any solution ??

Gidi
Gidi
5 years ago

I`m trying to use snackbar in my preference activity (that user can choose miles or km), and then undo it with the action on the snack bar. But i can`t put coordinator layout in my preference activity, can i?

Ravi Tamada
5 years ago
Reply to  Gidi

Which layout you are using in your preference activity?

Kunal Agrawal
Kunal Agrawal
5 years ago

Hi Ravi i am new to android develpoment,i m following ur codes for making a good app,in your last Material Design with Fragment i want to add your facebook like feed to home fragment i am unable to do that pls help me to add feed activity to home fragment.

Kunal Agrawal
Kunal Agrawal
5 years ago
Reply to  Kunal Agrawal

material theme closes my application when i open feed in it also i m unable to attach activity inside home fragment pls provide codes for it that will be relay helpful

Bilal Ilyas
Bilal Ilyas
5 years ago

Hi Ravi! Please can you upload a tutorial about how to sync data from server mysql with json in android app database.
Thanks in advance

G V Sharma
G V Sharma
5 years ago

how to show snackbar, if the event was in adapter class?
I mean other than Activity or fragments, like Application class, AppConfigClass or any BaseAdapter class, AppUtils class?

Macharia
Macharia
5 years ago

Hi Ravi..,I like your work,How can can I add a botton toolbar,is it the normal toolbar put at the bottom??

Trey Rosius
Trey Rosius
5 years ago

nice article Ravi…from your point of view, is it advisable to use libraries to facilitate programming?Is it a good practice, if i may ask.Like sometimes i get libraries of “ANDROID ARSENAL” and easily do stuff with.Is that good?

Renitto Jose
Renitto Jose
5 years ago
Reply to  Trey Rosius

@treyrosius:disqus I think using libraries for simple widgets like Snackbar is not a good practice, it will increase the size of your apk. Instead of applying the whole library in gradle download the library files and use only those java files you needed for your app.

Nirav Jain
Nirav Jain
5 years ago

hello. if you can write tutorial on group chat android app using php and mysql

Mohammad Zamani
Mohammad Zamani
5 years ago

Tnx Ravi

Okechukwu Eze
Okechukwu Eze
5 years ago

Hi :disqus
Can i add a multiple (two) action button to the snackBar like this ::

coordinatorLayout =(CoordinatorLayout) findViewById(R.id.coordinatorLayout);
Snackbar snackbar = Snackbar
.make(coordinatorLayout, ” ” + message + ” “, Snackbar.LENGTH_INDEFINITE)

.setAction(“BUTTON1”, new View.OnClickListener() {
@Override
public void onClick(View view) {

////ACTION

}
}).setAction(“BUTTON2”, new View.OnClickListener() {
@Override
public void onClick(View view) {

////ACTION

}
});

Is it suppose to work ?

The layout design for SnackBar

https://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-usage

has a two action button design.

SO HOW CAN I MAKE AN SNACKBAR WITH TWO ACTION BUTTONS

Srikar Reddy
5 years ago

Thanks for the tutorial Ravi. I’ve a query regarding the code.

In step 2 (Snackbar with Action Callback), when clicked on the “UNDO” action, Floating Action Bar went behind the Snackbar (at 0:15 in the video). How can we avoid this?

Uki
Uki
5 years ago

Thanks Ravi for gr8 tuts. I am learning from you more than 2 years, even got job as android developer a year ago.

What is the minimum Android API supported for this?

Ervan Prastyanto
Ervan Prastyanto
5 years ago

Ravi: Can you share article about Multiplayer Game With Bluetooth…? Thanks before

Anderson Madeira
5 years ago

Ravi, your tutorials are up to date, fully functional and very detailed! It’s just amazing! This is the first decent series of MaterialDesign tutorials I’ve found so far. Really worth reading. I’m anxious for the next tutorial. Keep up the good work!

Ravi Tamada
5 years ago

Thanks Anderson πŸ™‚

Manny264
Manny264
5 years ago

Hi Ravi,do you think maybe you can do a tutorial about Cards in Android??

Suleiman19
5 years ago

While Snackbar appears to be a simple layout component, I love your comprehensive take on it featuring a its customization options. However, I was wondering, is is possible to change the Snackbar’s background color?

Ravi Tamada
5 years ago
Reply to  Suleiman19

Yes, background color can be changed. As android guidelines suggested a specific color to background, I didn’t mentioned here.

You can change it like this

Snackbar snackbar = Snackbar.make(…)

View snackBarView = snackBar.getView();

snackBarView.setBackgroundColor(getResources().getColor(R.color.green));

Suleiman19
5 years ago
Reply to  Ravi Tamada

Thanks Ravi

Zak
Zak
5 years ago

Thanks Ravi for all the tutorial you made. I love you’re website !

Ravi Tamada
5 years ago
Reply to  Zak

You are welcome πŸ™‚

Manuel Salas
Manuel Salas
5 years ago

nice tutorial

Gabriel Alejandro Rodriguez
Gabriel Alejandro Rodriguez
5 years ago
Reply to  Manuel Salas

Tienes razon my friend

Manuel Salas
Manuel Salas
5 years ago

hahaha spanglish??

Gabriel Alejandro Rodriguez
Gabriel Alejandro Rodriguez
5 years ago
Reply to  Manuel Salas

more or menos

Manuel Salas
Manuel Salas
5 years ago

haha

Gabriel Alejandro Rodriguez
Gabriel Alejandro Rodriguez
5 years ago
Reply to  Manuel Salas

Ravi Tamada is great

Vaishakh Nambiar OK
Vaishakh Nambiar OK
5 years ago

thanku ravi. nice tutorial

Anshul Dhingra
Anshul Dhingra
5 years ago

Hi ravi thanx alot for this beautiful tutorial can you please also provide the tutorial of CollapsingToolbarLayout like in play store or you can say while we are looking whatsapp profile of someone, and like in google musicplayer app while we scroll currently playing song

Mehraj Malik
Mehraj Malik
5 years ago

The best tutorial award …… Thanxx alot sir

nawaf mushtaque ahmed
nawaf mushtaque ahmed
5 years ago

can we set custom views to snackbar

rvi
rvi
4 years ago

hy

Falmer Loremo
Falmer Loremo
4 years ago

The Best Site of Android. o/ Thanks for all !

Satyaki
Satyaki
4 years ago

Sir, if you provide some tutorial about developing Android Framework, then it will help us.

mojtaba
mojtaba
4 years ago

hi,how to create this in eclipse?

benju
benju
4 years ago
Reply to  mojtaba

Use Android Studio πŸ˜‰

Pooja Solanki
Pooja Solanki
4 years ago
Reply to  mojtaba

if you really want to use eclipse then add jar “android-support-design” to your project .
which is located in [sdk -root] extrasandroidsupportdesignlibs

then just write code normally.

TheIcemanCometh
TheIcemanCometh
4 years ago

Hi Ravi,

Great tutorial, but I believe the resource ID you want to use when changing the text color of the action button is “snackbar_action” instead of “snackbar_text” …

robert
robert
4 years ago

Learn android development by examples. https://android-by-examples.myshopify.com/

Nithya
Nithya
4 years ago

Hi Ravi,

Can you share the article about ” How to integrate Overview Screen in android application ” ?

TimeTraveler
TimeTraveler
4 years ago

Thanks for such an wonderful tutorial Ravi…

Daniel_Z
Daniel_Z
4 years ago

thanks! πŸ™‚

Webster Weby
Webster Weby
4 years ago

thanks a lot, i saved a lot of time because of this post. But how can i close the navigation drawer with back button? Now it’s only close if you drag the drawer to the left side, or you touch the right side (non drawer side). Thanks

Ravi Tamada
4 years ago
Reply to  Webster Weby

Override onBackpress method and call drawerlayout close method inside.

Webster Weby
Webster Weby
4 years ago
Reply to  Ravi Tamada

oopss sorry, wrong page to comment, actually i want to comment on this page http://www.androidhive.info/2015/04/android-getting-started-with-material-design/#disqus_thread, but somehow i ended up in this page, lol.

But you saved me once again, i added onKeyListener in the fragment and call drawerlayout close method when “back key” pressed.

Thanks a lot sir!

Ravi Tamada
4 years ago
Reply to  Webster Weby

You are welcome πŸ™‚

Huy
Huy
4 years ago

Thanks Ravi for all the tutorial you made. I love your website !

Chineye
Chineye
4 years ago

Thanks Ravi for the snackbar tutorial.i had some challenge with the com.android.support:design:23.0.1 library but i was able to resolve it

dony
dony
4 years ago

Hi, It’s really good example for me. But i have question. I want to show snack bar in activity1 when finished after something like as progress dialog dismiss and finish activity2. can I show snack bar in activity 1 like toast?

Akshay Patil
Akshay Patil
4 years ago

I know its silly but can anyone help. Am getting type mismatch: cannot convert from void to Snackbar

marielle
marielle
4 years ago

Hi, can you just explain why i cant have the same design (button position,edit text position…)in all the devices resolution and size.. what is the tip about having good design on any device (4.5″,5″,5.5″….)

Rishabh
Rishabh
4 years ago

Hi All,

I am facing some exception while executing “compile
org.apache.httpcomponents:httpmime:4.2.3″, i know the reason, there are
some classes in this dependency which is getting conflict with some
other class in app.
p.s:”Tired of googling this issue, stll unable to resolve frown emoticon !”
If anyone knows how to get rid of this issue kindly share, your solution will be appreciated smile emoticon !

Here are the logs:
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lorg/apache/http/annotation/GuardedBy;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
Error:Execution failed for task ‘:app:dexDebug’.

> com.android.ide.common.process.ProcessException:
org.gradle.process.internal.ExecException: Process ‘command ‘C:Program
FilesJavajdk1.7.0_40binjava.exe” finished with non-zero exit value 2
Information:BUILD FAILED

Abelardo
Abelardo
4 years ago

Hi everyone,

I copied this code into mine but this error was displayed:

java.lang.RuntimeException: Unable to start activity ComponentInfo{….}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.

Does anybody know why this message is displaying?

Ravi, your blog is superb. Thank for your support, time and to share your acknowledge with the rest of the world!

vinay
vinay
4 years ago

I need the design or style used in way2sms app. The new material design,swipe kind of concept. Could anyone help me thanks in advance.

Aiswarya olakkal
Aiswarya olakkal
4 years ago

thanks Ravi!.. It’s really good example for me.

vinod
vinod
4 years ago

how to fix snackbar permanent to the layout. and also when click on .setaction method to fix to the layout

Chansopheak Khun
Chansopheak Khun
4 years ago

how to set background color to snackbar? and also show animation?

Christopher Derrell
Christopher Derrell
3 years ago

After you do initialize the Snackbar, use View view = snackbar.getView(); view.setBackgroundColor(R.color.yourcolor).

Hosein Saad
Hosein Saad
4 years ago

@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_copy:
if(resultNumber.length() != 0){
Snackbar.make(?????? , “Done” , Snackbar.LENGTH_LONG).show();
}
return true;
}
return true;
}

what should I write instead of question marks?

Ravi Tamada
4 years ago
Reply to  Hosein Saad

You can use any view. If you don’t have Fab, use CoordinatorLayout instance.

Nouman Jamil
Nouman Jamil
3 years ago
Reply to  Ravi Tamada

if dont have coordinatorLayout ? if i am using RelativeLayout or LinearLayout ?

Sountharya M
Sountharya M
4 years ago

Hi ravi..Pls tell me How to reduce the height of snack bar?

ankesh kumar
ankesh kumar
3 years ago

Hi sir how to add more option in snack bar in hierarchical order with icons like below attached screen shot please help me. thanks in advance…..

in below screen at bottom of screen white part of screen just like that i want to design a snack bar
as camera and gallery with title displayed.
comment image

Oyedepo Olufemi
Oyedepo Olufemi
3 years ago

Hi Ravi, pls help. I’ve followed all the steps but my app crashes when i launch it.
Here is my logcat:

FATAL EXCEPTION: main

Process: com.codeinn.snackbardemo, PID: 1686

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.codeinn.snackbardemo/com.codeinn.snackbardemo.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.Toolbar cannot be cast to android.support.design.widget.FloatingActionButton

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

at android.app.ActivityThread.access$800(ActivityThread.java:144)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)

at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:135)

at android.app.ActivityThread.main(ActivityThread.java:5221)

at java.lang.reflect.Method.invoke(Native Method)

at java.lang.reflect.Method.invoke(Method.java:372)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Caused by: java.lang.ClassCastException: android.support.v7.widget.Toolbar cannot be cast to android.support.design.widget.FloatingActionButton

at com.codeinn.snackbardemo.MainActivity.onCreate(MainActivity.java:29)

at android.app.Activity.performCreate(Activity.java:5933)

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

at android.app.ActivityThread.access$800(ActivityThread.java:144)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)

at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:135)

at android.app.ActivityThread.main(ActivityThread.java:5221)

at java.lang.reflect.Method.invoke(Native Method)

Mehul Vasa
Mehul Vasa
3 years ago

Hello Guys, In device below lollypop, In some screens its showing the snackbar text in black and in some screens its showing snackbar text in white… What to do, can somebody help me out? πŸ™

kavie
kavie
3 years ago

Hi,

In 3. Customizing the Snackbar View

// Changing message text color – textView.setTextColor(Color.YELLOW);
// Changing action button text color – snackbar.setActionTextColor(Color.RED);

Please Change this.

81
0
Would love your thoughts, please comment.x
()
x