The Snackbar is a view that’s mostly used to give quick feedback to the user, like Toast. It appears at the bottom of the the screen and disappears after some timeout. Sometimes the user can “swipe” the Snackbar to make it disappear. But unlike Toast, you can put some actions in the Snackbar.

Figure 1. Snackbar example

Checklist before using Snackbar in your project

  1. Update the build.gradle file to include ‘com.android.support:design’ in the dependencies. Without this, you won’t be able to use the Snackbar control. In an Android Studio project, there are 2 gradle files. One is located on the project’s root folder and the other is inside the app folder. It’s the latter that we need to update
  2. Add an android:id attribute to the layout container.You will refer to it later when you use Snackbar. The layout container doesn’t have a View ID by default, so you need to put it in
  3. Import the Kotlin Android Extensions (KAE) in your MainActivity file. This is actually optional, but it would be nice if we can refer to View Ids without using findViewById(). The KAE synthesizes all the View Ids in the layout files and exposes them as extension properties of the class Listing 1. excerpt from app/build.gradle
dependencies {
  ...
  implementation "com.android.support:design:27.1.0"
}

Listing 2. excerpt from MainActivity.Kt

import kotlinx.android.synthetic.main_activity_main.* 

fun whenClicked(v:View) {
  snack=Snackbar.make(root_layout, "Hello", Snackbar.LENGTH_LONG)
  snack.show()
}

First line of Listing 2 imports the Kotlin Android Extension. This lets us refer to View elements using just their IDs.

Snackbar’s make() function takes 3 parameters, they are;

  1. the View ID of the layout container, this is why you need to put an android:id="root_layout" in the container
  2. the String message you want to show, and
  3. the amount of time, in milliseconds, that the message will be visible