Display Snackbar in Android

Display Snackbar in Android

A snackbar is a small banner that appears at the bottom of the screen. A snackbar provides a short message about running processes and automatically disappears after a few seconds.

Firstly, we need to add the Material Components dependency in the module's build.gradle file.

app/build.gradle

dependencies {
    // Other dependencies
    // ...
    implementation 'com.google.android.material:material:1.2.0'
}

In the layout XML file, we added a Button that will be used to display a snackbar. A parent view is required to create a snackbar. So we add the android:id attribute in the root layout.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Open" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

The method Snackbar.make() is used to create a snackbar. The last parameter is duration, which defines how long to display a snackbar.

ValueDescription
LENGTH_SHORTA snackbar will be shown for 1500 milliseconds.
LENGTH_LONGA snackbar will be shown for 2750 milliseconds.
LENGTH_INDEFINITEA snackbar will be shown until it is dismissed, or another snackbar is shown.
durationCustom duration in milliseconds.

The method show() is used to display a snackbar.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

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?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myButton.setOnClickListener { showSnackbar() }
    }

    private fun showSnackbar()
    {
        val snack = Snackbar.make(rootLayout, "Hello world", Snackbar.LENGTH_LONG)
        snack.show()
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.