Android Native - How to create Snackbars

dimitrilc 3 Tallied Votes 115 Views Share
Introduction

Snackbars are great for displaying brief messages providing feedback to your users.

In this tutorial, we will learn how to create Snackbars.

Goals

At the end of the tutorial, you would have learned:

  1. How to create a Snackbar.
Tools Required
  1. Android Studio. The version used in this tutorial is Arctic Fox 2020.3.1 Patch 4.
Prerequisite Knowledge
  1. Basic Android.
Project Setup

To follow along with the tutorial, perform the steps below:

  1. Create a new Android project with the default Empty Activity.
  2. Remove the “Hello World!” TextView from acitivity_main.xml.
  3. Add a new Button to activity_main.xml.
  4. Constraint the Button to all 4 sides of the ConstraintLayout.
  5. Extract the hard-coded android:text attribute of Button to a String resource and also change the value to “Load Data”.
  6. Add the attribute android:id="@+id/main" to the ConstraintLayout element in activity_main.xml.

Your activity_main.xml file should look similar to the code below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:id="@+id/main">

   <Button
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/button"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Snackbars Overview

Snackbar (com.google.android.material.snackbar.Snackbar) is a class in the Material Android library. Snackbars can only be added programmatically.
Snackbars display a brief message at the bottom of the screen and should disappear by themselves without user intervention.

Screenshot_1639071733.png

Snackbars should NOT be intrusive to your users, so you should follow Material Design guidelines here when using Snackbars.

Bind Button to Snackbar

Before getting into making the Snackbar, let us bind the Button to an action first. Our desired program will display a Snackbar stating that the Application is unable to load data right now, and advise the user to try again in a few seconds.

Loading data is out of scope for this tutorial, so our program will always show the Snackbar on button presses to only simulate the behavior of a Snackbar.

  1. In Main.Activity.kt, create a function called bindButton() to bind the Button to an action. At this point, the onClickListener is just empty.

     private fun bindButton(){
        val button = findViewById<Button>(R.id.button)
    
        button.setOnClickListener {
        }
     }
  2. Next, call it in onCreate().

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bindButton()
     }
Creating Snackbar objects

To create Snackbars, we need to use the Snackbar.make() functions. The function that we will use in this tutorial is

public static Snackbar make (View view, 
                int resId, 
                int duration)

The 3 arguments that we need to provide are the parent for the Snackbar to appear in, the resource ID for the Snackbar text, and the duration (in milliseconds) for the Snackbar to disappear.

For the duration argument, you can also use the predefined constants that Snackbar inherited from BaseTransientBottomBar, namely:

  1. Snackbar.LENGTH_SHORT
  2. Snackbar.LENGTH_LONG
  3. Snackbar.ENGTH_INDEFINITE

Follow the steps below to create a Snackbar:

  1. In strings.xml, add the String resource below. This String resource will be used as the Snackbar text.

     <string name="snackbar_loading_fail">Can\'t load data. Retry in 5 seconds.</string>
  2. In the function findButton(), add the lines of code below to create references to the ConstraintLayoutView as well as the Snackbar text.

     val mainView = findViewById<ConstraintLayout>(R.id.main)
     val error = getString(R.string.snackbar_loading_fail)
  3. In findButton(), create the Snackbar object and assign it to the snackbar variable .

     val snackbar = Snackbar.make(
        mainView,
        error,
        Snackbar.LENGTH_SHORT)
  4. The Snackbar will not do anything unless we call the function show() on it. Inside the setOnClickListener block, call show() on the snackbar reference.

     snackbar.show()
  5. Your bindButton() function should now look like this:

     private fun bindButton(){
        val button = findViewById<Button>(R.id.button)
        val mainView = findViewById<ConstraintLayout>(R.id.main)
        val error = getString(R.string.snackbar_loading_fail)
    
        val snackbar = Snackbar.make(
            mainView,
            error,
            Snackbar.LENGTH_SHORT)
    
        button.setOnClickListener {
            snackbar.show()
        }
     }
Run the App

We are now ready to run our App.

When you press the Load Data Button, you will see the Snackbar appears at the bottom of the screen and disappears after a few seconds.

Snackbar_Final.gif

Solution Code

MaintActivity.kt

package com.example.daniwebsnackbar

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)
       bindButton()
   }

   private fun bindButton(){
       val button = findViewById<Button>(R.id.button)
       val mainView = findViewById<ConstraintLayout>(R.id.main)
       val error = getString(R.string.snackbar_loading_fail)

       val snackbar = Snackbar.make(
           mainView,
           error,
           Snackbar.LENGTH_SHORT)

       button.setOnClickListener {
           snackbar.show()
       }
   }
}

strings.xml

<resources>
   <string name="app_name">Daniweb Snackbar</string>
   <string name="button">Load Data</string>
   <string name="snackbar_loading_fail">Can\'t load data. Retry in 5 seconds.</string>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:id="@+id/main">

   <Button
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/button"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Summary

We have learned how to create Snackbars. The full project code can be found here https://github.com/dmitrilc/DaniwebSnackbar.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.