So it’s been quite a while since Android introduced it’s guidelines for Material Design. Even Material 2.0 has come out recently which has many things. But, our main concern here will be implementing the Android Snackbar from Material Design.

What is Snackbar ?

Snackbar in Android is a new widget API which was made available to make more attractive applications. It is simply a replacement for the toast which we used to display some short popup like messages.

They are drop in replacement which must adhere to the Material Design guidelines provided. Also you cannot just call Snackbar from anywhere. Which is if you want to follow the material design guidelines.

Anatomy of the Snackbar

Here let us look at a snackbar and define each components

Image from: material.io

1 is the text label of the snackbar. While 2 being the container and 3 is the action in the snackbar.

You can manipulate this elements to some extent. Though I will not be covering all the customizations. I will be mentioning this later in this article.

Also Read : Learn how to use fileprovider in Android with example

TECHENUM

Toast vs Snackbar

Now what do I mean by vs ? Am I trying to take one side ? Obviously NO.

They both have their own weakness or strengths let us quickly see what are they.

Toasts can be called from anywhere as long as the right context is passed for them. Else you will see a runtime exception. Oh and they must be called on the Main Thread or UI Thread.

// toast code snippet
Toast.makeText(context, "Techenum is awesome!", Toast.LENGTH_LONG).show()Code language: Kotlin (kotlin)

On the other hand Snackbar are replacement for the toast. But do not get confused with the term replacement. Snackbar are not only attractive but also a little more flexible than toasts. And IMO looks much more neat and nicer.

// example of snackbar
val snackbar: Snackbar = Snackbar.make(coordinatorLayout, "http://nepdev.xyz", Snackbar.LENGTH_LONG)
snackbar.show();
Code language: JavaScript (javascript)

Aside from this toast can be positioned anywhere on the screen. But the Snackbar must be shown at the very bottom of the screen. Though snackbar can be anchored to any visible view. It is just a basic guideline for implementing the Snackbar.

That was a quick contrast between Toast and Snackbar.

Including the material library for Android

Before you can even use the Snackbar or other material components you have to include the material dependency in your gradle. You can do that by adding the code below in your app > build.gradle.

implementation 'com.google.android.material:material:1.2.0'Code language: JavaScript (javascript)

One you perform the gradle sync all the material components will be available.

Let us talk a little more about Snackbar and look at how it really works.

Snackbar has static method to show a the popup message to the user. But according to the material guidelines the nearest CoordinatorLayout must be passed. If CoordinatorLayout is not available you should pass in the DecorView.

And for the duration the length must be passed in form of predefined constant. Which again is accessible in form of static variable.

Available time duration are listed under:

  • LENGTH_INDEFINITE will make sure the Snackbar is shown for indefinite amount of time.
  • LENGTH_LONG makes the Snackbar visible for a longer duration, and
  • LENGTH_SHORT will make the Snackbar visible for only a short amount of time

Also Read : Learn How To Create Tabs With ViewPager2

TECHENUM

Setting up the layout for Snackbar

Let us setup a simple activity with CoordinatorLayout and a FloatingActionButton so that we can emulate any action.

For that we have created a MainActivity class with the code below for layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floating_action_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>Code language: HTML, XML (xml)

In the code above I have set the root element to CoordinatorLayout. I have included all our elements inside the ConstraintLayout. Also, I have added a FloatingActionButton which will be clicked to show the Snackbar.

Now that we have our UI ready let us map it to our MainActivity as below:

class MainActivity : AppCompatActivity() {

    private lateinit var mCoordinatorLayout: CoordinatorLayout
    private lateinit var mFloatingActionButton: FloatingActionButton

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mCoordinatorLayout = findViewById(R.id.coordinator_layout)
        mFloatingActionButton = findViewById(R.id.floating_action_button)
        mFloatingActionButton.setOnClickListener {
            // noAction()
        }

    }

}Code language: Kotlin (kotlin)

Snackbar without any customization

Now that we have our code ready. Let us add the actual Snackbar.

Copy the following block of code inside your MainActivity class.

    private fun noAction() {
        Snackbar.make(mCoordinatorLayout, "This is a simple message.", Snackbar.LENGTH_LONG)
            .show()
    }Code language: Kotlin (kotlin)

That is pretty much it all you have to do now is un-comment the code inside the click listener of FloatingActionButton. Un-comment the following line

// noAction()Code language: Kotlin (kotlin)

Also Read : Async Task in Android is Deprecated: There are Better Ways

TECHENUM

Snackbar with an action button

Now that we have seen a simple Snack bar let us look at another possibility provided by the snackbar. The click action you can have with a custom text.

I have created another method named simpleAction() { } copy this in your MainActivity class too and use it whenever required.

private fun simpleAction() {
    Snackbar.make(mCoordinatorLayout, "This is a simple message.", Snackbar.LENGTH_LONG)
        .setAction("Undo") {
            noAction()
        }.show()
}Code language: Kotlin (kotlin)

The code inside .setAction(“your text”) { // action here } block is for the action you will see on the Snackbar.

That is all you need to add an action, it’s really very easy.

Customizing the Android Snackbar as per Material Design

Up to this point the Snackbar works but it looks really very basic. Let us quickly learn to change that.

Since our Snackbar isn’t looking attractive let us just make it look more attractive. For that let us change some styles.

Before moving forward you have to make sure that the your application’s theme is extending one of the material themes.

For this tutorial I have used the Theme.MaterialComponents.DayNight but you can use any other material parents.

Add the following style in your styles.xml

<!-- custom snack bar -->
<style name="CustomSnackBar" parent="Widget.MaterialComponents.Snackbar">
    <item name="android:layout_margin">16dp</item>
</style>Code language: HTML, XML (xml)

What it does is that it adds the 16dp margin around the Snackbar.

Apply the style to whole application by adding it in the theme of your application. Do notice the snackbarStyle here

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="snackbarStyle">@style/CustomSnackBar</item>

</style>Code language: HTML, XML (xml)

If you run your application at this point it will be a bit more attractive than before. We can live with what we have achieved.

Here are some of the attributes you can play with further with the actual wrapper for Snackbar.

AttributeDefault value
Colorapp:backgroundTint?attr/colorSurface at 80% over ?attr/colorOnSurface
Color overlay alphaapp:backgroundOverlayColorAlpha0.8f (ignored if app:backgroundTint is set)
Marginandroid:layout_margin8dp
Elevationapp:elevation6dp
Animation modeapp:animationModefade
Taken from official guidelines: material.io

I haven’t really touched most of it because in normal use-case you don’t really need to touch most of it.

And that is all your snackbar will automatically respect the styles defined in base application theme.

Also Read : ZOOM SDK Android: Learn How to Create an Online Meeting

TECHENUM

What if you don’t use a CoordinatorLayout ?

This is a really good question. And has a valid issue raised. You application might not have used the material guidelines, which is perfectly fine.

If you want to use Snackbar in such situation you can pass in the window.decorView.rootView instead of the CoordinatorLayout.

Also, it is worth mentioning that you lose all the benefits of using a CoordinatorLayout such as anchoring and auto layout adjust with FloatingActionButton or BottomNavigationView.

And please do remove all the material styling from styles.xml for Snackbar if you’re not using the material theme. Leaving it there will cause your application to crash.

You have to go to lengths to make adjustments to your Snackbar. Which is beyond the scope of this article, so might be some other day.

That is it you have learned android snackbar with the material design guidelines. Also, I will be updating the article with GitHub link for android snackbar, soon.

Also Read : Implement SMS Broadcast Receiver in Android

TECHENUM

Related Posts