Android Snackbar(Java/Kotlin)

This article is about Android Snackbar and how to use it in android application with simple examples in Java and Kotlin.

Snackbar

Snackbar is an Android Material Design component . It provide lightweight response about an operation by showing a short message at the bottom of the screen on mobile and lower left on larger devices.

A Snackbar can contain an optional action button to perform action, such as undoing an action or retrying an action.

Only one snackbar will be shown at a time.

Snackbar disappear either after a timeout or after a user interaction elsewhere on the screen (particularly after interactions that invites a new surface or activity), but can also be swiped off the screen.

Note: Snackbars work best if they are displayed inside of a CoordinatorLayout. CoordinatorLayout allows the snackbar to enable behavior like swipe-to-dismiss, as well as automatically moving widgets like FloatingActionButton.

Simple Snackbar

The below code snippet is an example of Simple Snackbar

Snackbar snackbar = Snackbar.make(constraintLayout, "Simple Snackbar ", Snackbar.LENGTH_LONG);
snackbar.show();

The make function accepts three parameters:

View : Used to find a parent view to hold Snackbar’s view.

CharSequence: The text to show on snackbar.

Duration : How long to display the message. It can be LENGTH_SHORT, LENGTH_LONG, LENGTH_INDEFINITE or a custom duration in milliseconds.

  • LENGTH_SHORT: Show the Snackbar for a short period of time.
  • LENGTH_LONG: Show the Snackbar for a long period of time.
  • LENGTH_INDEFINITE: Show the snackbar until it’s either dismissed or another snackbar is shown.

show(): Used to display the Snackbar on the screen.

Android Default Snackbar

Snackbar with Action

You can add an action to a Snackbar , allowing the user to respond to your message.

To add an action, use the setAction method on the object returned from make. Snackbars are automatically dismissed when the action is clicked.

setAction(): Set the action to be displayed in the Snackbar. It takes two parameters:

  • text: Text to display for the action
  • listener: callback to be invoked when the action is clicked.

The below code snippet is an example of how to show a snackbar with a message and an action:

Snackbar snackbarWithAction = Snackbar.make(constraintLayout, "Contact removed", Snackbar.LENGTH_LONG);

//get snackbar view
View snackbarView = snackbarWithAction.getView();

//get snackbar child views
TextView snackbarText = (TextView) snackbarView.findViewById(R.id.snackbar_text);
TextView snackbarActionText = (TextView) snackbarView.findViewById(R.id.snackbar_action);

//change snackbar text color
snackbarText.setTextColor((Color.CYAN));

//change snackbar action button text color
snackbarActionText.setTextColor((Color.RED));

//use setAction() to add action UNDO
snackbarWithAction.setAction("UNDO", new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Snackbar snackbar = Snackbar.make(constraintLayout, "The contact is restored", Snackbar.LENGTH_LONG);

        View snackbarView = snackbar.getView();

        //change snackbar background color   
        snackbarView.setBackgroundColor(getResources()
        .getColor(R.color.green));

        TextView snackbarText = (TextView) snackbarView.findViewById(R.id.snackbar_text);

        //change snackbar text color
        snackbarText.setTextColor((Color.WHITE));

        //change snackbar text gravity
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
            snackbarText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        else {
            snackbarText.setGravity(Gravity.CENTER_HORIZONTAL);
        }
        snackbar.show();
    }
});
//show snackbar
snackbarWithAction.show();
Snackbar with Action
Show snackbar with text (center) on click of UNDO button

Snackbar with Custom View

Android Snackbar allows you to create a customized layout for your snackbar.

To create a custom layout, define a View layout, in XML. The following snippet contains a customized layout for snackbar (saved as layout/custom_snackbar.xml):

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/custom_snackbar_container"
    android:background="@android:color/holo_orange_light">

    <ImageView
        android:id="@+id/iv_custom_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/margin_10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/tv_custom_view"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/ic_dialog_alert" />

    <TextView
        android:id="@+id/tv_custom_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_external_storage_available"
        android:textColor="@android:color/black"
        android:textSize="@dimen/textsize_15sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/iv_custom_view"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

You must use the ID of the ConstraintLayout element ( “custom_snackbar_container“) and the ID of the XML layout file “custom_snackbar.xml” to inflate the layout, as shown here:

//get created custom layout of snackbar
View customSnackBarView = getLayoutInflater().inflate(R.layout.custom_snackbar, (ViewGroup) findViewById(R.id.custom_snackbar_container));

Now pass this View object (created using custom layout) to the addView() method.

Snackbar customSnackBar = Snackbar.make(constraintLayout, "", Snackbar.LENGTH_LONG);

Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) customSnackBar.getView();

//get snackbar custom layout
View customSnackBarView = getLayoutInflater().inflate(R.layout.custom_snackbar, (ViewGroup) findViewById(R.id.custom_snackbar_container));

//add snackbar custom layout
layout.addView(customSnackBarView, 0);

customSnackBar.show();
Snackbar with custom layout

Creating New Project

1. In Android Studio, go to File ⇒ New Project, fill all the details required to create a new project and then click on finish.

2. Open build.gradle (app level), add the material dependency as shown below and then sync your project:

build.gradle

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

3. Rename the layout file activity_main.xml as activity_snackbar.xml and add the below code. This layout file consist of three buttons, SIMPLE SNACKBAR (To show Android standard snackbar), SNACKBAR WITH ACTION (To show snackbar with action), SNACKBAR WITH CUSTOM VIEW (To show snackbar with custom view).

activity_snackbar.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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/margin_20dp"
    tools:context=".SnackbarActivityJava">

    <Button
        android:id="@+id/btn_simple_snackbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/simple_snackbar"
        android:padding="@dimen/padding_12dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_snackbar_with_action"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />


    <Button
        android:id="@+id/btn_snackbar_with_action"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_10dp"
        android:layout_marginBottom="@dimen/margin_10dp"
        android:text="@string/snackbar_with_action"
        android:padding="@dimen/padding_12dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_snackbar_with_custom_view"
        app:layout_constraintEnd_toEndOf="@+id/btn_simple_snackbar"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="@+id/btn_simple_snackbar"
        app:layout_constraintTop_toBottomOf="@+id/btn_simple_snackbar" />

    <Button
        android:id="@+id/btn_snackbar_with_custom_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/snackbar_with_custom_view"
        android:padding="@dimen/padding_12dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/btn_snackbar_with_action"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="@+id/btn_snackbar_with_action"
        app:layout_constraintTop_toBottomOf="@+id/btn_snackbar_with_action" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. Create a new layout file custom_snackbar.xml (layout->New->Layout Resource File) and add the below code. This layout file represents the custom layout of snackbar.

custom_snackbar.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/custom_snackbar_container"
android:background="@android:color/holo_orange_light">

<ImageView
android:id="@+id/iv_custom_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/margin_10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/tv_custom_view"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@android:drawable/ic_dialog_alert" />

<TextView
android:id="@+id/tv_custom_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_external_storage_available"
android:textColor="@android:color/black"
android:textSize="@dimen/textsize_15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/iv_custom_view"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Complete code in Java

Create a new activity SnackbarActivityJava.java This activity contains three buttons with click listener to show the different ways of implementing the Snackbar in Java.

SnackbarActivityJava.java

package com.c1ctech.androidsnackbardemo;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

public class SnackbarActivityJava extends AppCompatActivity implements View.OnClickListener {

    private Button btnSimpleSnackbar, btnSnackbarWithAction, btnCustomSnackbar;
    private ConstraintLayout constraintLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_snackbar);

        //get parent view by its id
        constraintLayout = findViewById(R.id.constraintLayout);

        //get child views of constraintLayout by its id
        btnSimpleSnackbar = findViewById(R.id.btn_simple_snackbar);
        btnSnackbarWithAction = findViewById(R.id.btn_snackbar_with_action);
        btnCustomSnackbar = findViewById(R.id.btn_snackbar_with_custom_view);

        //setting listener to each button
        btnSimpleSnackbar.setOnClickListener(this);
        btnSnackbarWithAction.setOnClickListener(this);
        btnCustomSnackbar.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();
        switch (id) {
            case R.id.btn_simple_snackbar:
                Snackbar.make(constraintLayout, "Simple Snackbar ", Snackbar.LENGTH_LONG).show();
                break;

            case R.id.btn_snackbar_with_action:
                Snackbar snackbarWithAction = Snackbar.make(constraintLayout, "Contact removed", Snackbar.LENGTH_LONG);

                //get snackbar root view
                View snackbarView = snackbarWithAction.getView();

                //getting child views of snackbar
                TextView snackbarText = (TextView) snackbarView.findViewById(R.id.snackbar_text);
                TextView snackbarActionText = (TextView) snackbarView.findViewById(R.id.snackbar_action);

                //change snackbar text color
                snackbarText.setTextColor((Color.CYAN));

                //change snackbar action button text color
                snackbarActionText.setTextColor((Color.RED));

                snackbarWithAction.setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Snackbar snackbar = Snackbar.make(constraintLayout, "The contact is restored", Snackbar.LENGTH_LONG);

                        View snackbarView = snackbar.getView();

                        //change snackbar background color
                        snackbarView.setBackgroundColor(getResources().getColor(R.color.green));

                        TextView snackbarText = (TextView) snackbarView.findViewById(R.id.snackbar_text);

                        //change snackbar text color
                        snackbarText.setTextColor((Color.WHITE));

                        //change snackbar text gravity
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
                            snackbarText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                        else {
                            snackbarText.setGravity(Gravity.CENTER_HORIZONTAL);
                        }
                        //show snackbar
                        snackbar.show();
                    }
                });
                //show snackbar
                snackbarWithAction.show();
                break;

            case R.id.btn_snackbar_with_custom_view:

                Snackbar customSnackBar = Snackbar.make(constraintLayout, "", Snackbar.LENGTH_LONG);

                Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) customSnackBar.getView();

                //get created custom layout of snackbar
                View customSnackBarView = getLayoutInflater().inflate(R.layout.custom_snackbar, (ViewGroup) findViewById(R.id.custom_snackbar_container));

                //getting views from snackbar custom layout
                TextView textView = (TextView) customSnackBarView.findViewById(R.id.tv_custom_view);
                ImageView imageView = (ImageView) customSnackBarView.findViewById(R.id.iv_custom_view);

                //set text in snackbar custom layout textview
                textView.setText(getResources().getText(R.string.no_external_storage_available));

                layout.setPadding(0, 0, 0, 0);

                //add snackbar custom layout
                layout.addView(customSnackBarView, 0);

                //show snackbar
                customSnackBar.show();
                break;

        }
    }
}

When you run the application it will look like this:

Complete code in Kotlin

Create a new activity SnackbarActivityKotlin.kt (New->Activity->Empty Activity->select language kotlin) and then click on finish.This activity contains three buttons with click listener to show the different ways of implementing the snackbar in Kotlin.

SnackbarActivityKotlin.kt

package com.c1ctech.androidsnackbardemo

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.SnackbarLayout

class SnackBarActivityKotlin : AppCompatActivity(), View.OnClickListener {

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

        //get views by its id
        val btnSimpleSnackbar = findViewById<Button>(R.id.btn_simple_snackbar)
        val btnSnackbarWithAction = findViewById<Button>(R.id.btn_snackbar_with_action)
        val btnCustomSnackbar = findViewById<Button>(R.id.btn_snackbar_with_custom_view)

        //setting listener to each button
        btnSimpleSnackbar.setOnClickListener(this)
        btnSnackbarWithAction.setOnClickListener(this)
        btnCustomSnackbar.setOnClickListener(this)
    }

    override fun onClick(view: View) {

        //get parent view by its id
        val constraintLayout = findViewById<ConstraintLayout>(R.id.constraintLayout)

        val id: Int = view.getId()
        when (id) {
            R.id.btn_simple_snackbar -> Snackbar.make(constraintLayout, "Simple Snackbar ", Snackbar.LENGTH_LONG).show()
            R.id.btn_snackbar_with_action -> {
                val snackbarWithAction = Snackbar.make(constraintLayout, "Contact removed", Snackbar.LENGTH_LONG)
                val snackbarView = snackbarWithAction.view   //get snackbar root view

                //getting child views of snackbar
                val snackbarText = snackbarView.findViewById<View>(R.id.snackbar_text) as TextView
                val snackbarActionText = snackbarView.findViewById<View>(R.id.snackbar_action) as TextView

                //change snackbar text color
                snackbarText.setTextColor(Color.CYAN)

                //change snackbar action button text color
                snackbarActionText.setTextColor(Color.RED)
                snackbarWithAction.setAction("UNDO") {
                    val snackbar = Snackbar.make(constraintLayout, "The contact is restored", Snackbar.LENGTH_LONG)
                    val snackbarView = snackbar.view

                    //change snackbar background color
                    snackbarView.setBackgroundColor(resources.getColor(R.color.green))
                    val snackbarText = snackbarView.findViewById<View>(R.id.snackbar_text) as TextView

                    //change snackbar text color
                    snackbarText.setTextColor(Color.WHITE)

                    //change snackbar text gravity
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) snackbarText.textAlignment = View.TEXT_ALIGNMENT_CENTER else {
                        snackbarText.gravity = Gravity.CENTER_HORIZONTAL
                    }
                    //show snackbar
                    snackbar.show()
                }
                //show snackbar
                snackbarWithAction.show()
            }
            R.id.btn_snackbar_with_custom_view -> {
                val customSnackBar = Snackbar.make(constraintLayout, "", Snackbar.LENGTH_LONG)
                val layout = customSnackBar.view as SnackbarLayout

                //get created custom layout of snackbar
                val customSnackBarView = layoutInflater.inflate(R.layout.custom_snackbar, findViewById<View>(R.id.custom_snackbar_container) as? ViewGroup)

                //getting views from snackbar custom layout
                val textView = customSnackBarView.findViewById<TextView>(R.id.tv_custom_view)
                val imageView = customSnackBarView.findViewById<ImageView>(R.id.iv_custom_view)

                //set text in snackbar custom layout textview
                textView.text = resources.getText(R.string.no_external_storage_available)
                layout.setPadding(0, 0, 0, 0)

                //add snackbar custom layout
                layout.addView(customSnackBarView, 0)

                //show snackbar
                customSnackBar.show()
            }
        }
    }
}

Leave a Reply