Skip to main content

Snackbar in Android

How to make Snackbar in Android


Today. we are going to learn how to make a Snackbar in Android.

There are many ways to show short information but generally, we use toast messages and we have a snackbar.

Before going to implementation we should know the difference between the toast and snackbar.

If you want to show the only information then you should use toast but if you want to show some information with some action to be performed then it is recommended to use a snackbar with action.

You can customize the position of toast but the snackbar only shows from the bottom of the screen.

Now let's see how we can make a simple snackbar and also snackbar with the actin button.

How to make a simple snackbar?

Let's start by making a new project in the android studio if you not created already.

After that, we need to add a dependency to our project.

Add this dependency and hit the sync button.


After adding the dependency, go to the activity xml file and add the id to the parent layout and also we added a button to trigger the snackbar.


Now, open your activity java file and add this code.


First, we initialize a button with the findViewById method and set a click listener to it.

In the listener, we are getting the parent view by findViewById and pass the parent layout id.

After that, We are showing the snackbar which has three parameters, one is for a view where we are passing the parent view variable, second is a text which will be shown in the snackbar and the last parameter is for the duration just like toast has.

After passing the parameters, we need to call show function to show the snackbar.

Now, run your app and see the nice and beautiful snackbar like below.



How to make a snackbar with an action button?

Making a snackbar with an action button is very easy if you know how to make simple snackbar we need to just follow the above steps and call this function of snackbar like below.



In this function, first, we need to pass text which we will show on the button.

After that, we add a click listener just like we add in a simple button in android and write our logic.

We are showing a toast message on the click of the snackbar button.

After this, run your app and see how the action button will appear along with the snackbar.


That's it for today. If you learn something new then do share with your friends and mates.

Thank You for reading. Have a good day :)

Popular Posts

Customize rating bar in android

Working with Bottom Navigation bar in Android [Full Guide]

Custom Switch in Android | Akshayrana.in | Android Tutorial