Android Snackbar Example

In this tutorial you will learn about android snackbar example.

Snackbar is a new UI widget introduced in material design. It is an advance version or we can say replacement of Toast widget. Snackbar is used to display a short message at the bottom of screen. The message can be dismissed by swiping it.

Also Read: Android Custom Toast Example

Toast vs Snackbar

  • Toast can be placed anywhere on the screen while Snackbar can be placed at bottom only.
  • Toast can’t have a button while Snackbar can have at most one action button.
  • Toast message can’t be dismissed before its time period. Snackbar message can be dismissed by just swiping it.

 

Simple Snackbar

We can make a Snackbar by writing following line of code:

 

The make() method takes 3 arguments.

First Argument: It is the root layout for activity. Here we have used CoordinatorLayout because it gives some extra functionality to Snackbar like if we have used floating button then when Snackbar is displayed the floating button automatically goes up to provide space for Snackbar. By using CoordinatorLayout we can also dismiss the Snackbar by swiping.

Second Argument: It is the message that you want to display in Snackbar.

Third Argument: Time period for which Snackbar should be displayed.

  • Snackbar.LENGTH_SHORT: Display for short time period
  • Snackbar.LENGTH_LONG: Display for long time period
  • Snackbar.LENGTH_INDEFINITE: Displayed until you close it.

 

Snackbar with Action Button

You can also add an action button in Snackbar by using setAction() method. It can be done in following way.

 

You can’t add more than one button.

 

Customizing Snackbar

We can change color of text of message and action button in following way.

 

Android Snackbar Example

Below example shows how to make different types of Snackbar in android.

Create a new project with package name com.snackbarexample.

 

Note: Make sure you add dependency for android design support library in build.gradle (Module:app) file. Just add following line under dependency section and sync the project.

The library version may vary depending upon your SDK version.

 

Now add following code in respective files.

activity_main.xml

 

content_main.xml

 

MainActivity.java

 

Now save and run your project.

 

Screenshot

Android Snackbar Example

 

Comment below if you are facing any problem related to above android snackbar example.

1 thought on “Android Snackbar Example”

Leave a Comment

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