Home » Android Snackbar Example Kotlin

Android Snackbar Example Kotlin

android snackbar example kotlin

In this post, we are going to implement an Android Snackbar using Kotlin with an example. Android Snackbar is a user interface widget that was introduced in the material design library. And it is used to display small messages or feedbacks as similar to Toast. Snackbar and Toast are not the same. Here are some differences.

Difference Between Snackbar and Toast

Snackbar Toast
We can have a button inside a Snackbar. Whereas we can’t have a button inside a Toast message.
Usually, Snackbar is placed at the bottom of the screen. Toast message can be placed at any position on the screen
Snackbar messages are shown to the user for a few seconds. This message can be dismissed by swiping it. Users can’t dismiss the Toast message.

In the following Android Snackbar example, I have defined a button named “Simple Snackbar” when a user clicks this button a Snackbar will be shown.

Android Kotlin – Snackbar Example

To show a Snackbar on the screen, we write the code as shown below.

Snackbar.make(coordinatorLayout ,"This is a simple SnackBar",Snackbar.LENGTH_LONG).show()

In the above line of code make() method takes three parameters the first parameter is the root layout to display Snackbar, the second parameter takes a text message, and the last parameter takes duration.

The duration parameter can be one of these three values Snackbar.LENGTH_SHORT (for a short period of time), Snackbar.LENGTH_LONG (for a long period of time) and Snackbar.LENGTH_INDEFINITE (Snackbar will not disappear until the user interacts with it or until the application is closed).

Let’s start writing our application, The first thing to do is to add the material dependencies in build.gradle (Module: app).

implementation 'com.google.android.material:material:1.1.0'

After adding the required dependencies. Next, I have added the following code.


<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:text="Simple SnackBar"
        app:layout_constraintTop_toTopOf="parent" />

package com.example.snackbarexample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        simpleSnackBar.setOnClickListener {
            Snackbar.make(coordinatorLayout ,"This is a simple SnackBar",Snackbar.LENGTH_LONG).show()

Here is the output after running the application.

snackbar example android kotlin

Check: How to Change Snackbar Text and Background Color

Leave a Reply

Your email address will not be published.