UI/UX

Android Snackbar Example

In this post, we’ll learn implementation of various form of Android Snackbar widget in our application. It is an interesting component of the Material Design library. Android Snackbar is replacement of a Toast and they provide action to interact with. This blog explains about Snackbar with few examples.

What is Android Snackbar

Android Snackbar used to show feedback of certain operation just like Toast. They show a message at the bottom of the device screen. Snackbar appear on the above of all other element on device screen and displayed for some time. They automatically disappear after timeout or after user interaction. Snackbar can be swiped off in order to dismiss them.

Use Case of Android Snackbar

Followings are use case of Snackbar in Android

  • Normal Snackbar
  • Snackbar with Action

1. Normal Snackbar

The below code snippet is an example of Snackbar in Android.

Snackbar.make(@NonNull View view, @NonNull CharSequence text,@NonNull int duration);

Snackbar class has a static method named make() that accepts three parameters. First, one is View (it used to find a suitable ancestor to display Snackbar).

Second is CharSequence or a resource ID (The text to show. Can be formatted text ) and the third one this duration (How long to display the message It can be LENGTH_SHORT, LENGTH_LONG, LENGTH_INDEFINITE or a custom duration in milliseconds.). Every parameter is annotated with @NonNull that means they should not be null.

Snackbar behaviors are best with CoordinatorLayout.  They allow the Snackbar to enable behavior like swipe to dismiss, as well as automatically moving widgets just like FloatingActionButton.

Real Implementation of Snackbar

This is a real Implementation of Snackbar.

    // find the CoordinatorLayout id
    View contextView = findViewById(android.R.id.content);
    // Make and display Snackbar
    Snackbar.make(contextView, "Android Snackbar Example", Snackbar.LENGTH_SHORT)
        .show();

2. Snackbar with Action

Snackbar allows us to take certain action when user interacts with the Snackbar. that allows us to take action when user interacts with the snackbar action button

 // find the CoordinatorLayout id
    View contextView = findViewById(android.R.id.content);
    // Make and display Snackbar
    Snackbar snackbar =
        Snackbar.make(contextView, "Internet connection is lost", Snackbar.LENGTH_SHORT);
    // Set action with Retry Listener   
    snackbar.setAction("Retry", new TryAgainListener());
  
    // show the Snackbar
    snackbar.show();
TryAgainListener is

That listener handles the onClick() event of Retry button click

  public class TryAgainListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
      // Code to undo the user's last action
      View contextView = findViewById(android.R.id.content);
      // Make and display Snackbar
      Snackbar.make(contextView, "Internet connected", Snackbar.LENGTH_SHORT)
          .show();
    }
  }

3. Customize your Android Snackbar

Android Snackbar does not allow set custom layout. But it follows builder pattern which allows for easy styling. Let’s see the below figure.

material design

Snackbar provide builder methods for settings action text color like below.

Style Action Text color
snackbar.setActionTextColor(colorId)
Style text color, font, and text size and number of lines, etc.

Snackbar builder methods directly not provide such things. For doing that we’ll have to fetch the View first.

View snackbarView = snackbar.getView();

Now get TextView from View and apply all TextView properties as below

TextView textView = snackbarView.findViewById(R.id.snackbar_text);
// set no of text line
textView.setMaxLines(2);
//set text color
textView.setTextColor(colorId);
//set text size
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
Background color
  snackbarView.setBackgroundColor(colorId);

Android Snackbar Example Application

All conceptual part is done, let’s move to some real implementation. Open the Android Studio project and create a new project. You guys know well android redesign all design and support library and combined in two library androidx and material io

1. Open the app build.gradle add material dependencies
  implementation 'com.google.android.material:material:1.0.0'
2. Add some color in resource file that we’ll use in this demo app
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorPrimary">#2196F3</color>
  <color name="colorPrimaryDark">#1976D2</color>
  <color name="colorAccent">#FFEB3B</color>
  <color name="actionTextColor">#E64A19</color>
  <color name="colorBg">#FBE9E7</color>
</resources>
3. I have made few changes in style.xml
  <style name="btnStyle"  parent="TextAppearance.AppCompat.Widget.Button" >
    <item name="android:textColor">#fff</item>
    <item name="android:background">@color/colorPrimaryDark</item>
    <item name="android:layout_margin">16dp</item>
    <item name="android:padding">16dp</item>
    <item name="android:layout_width">240dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textAllCaps">false</item>
  </style>
4. Open activity_main.xml and add below component

Inside this layout, I have added some button for display different implementation of Snackbar

<?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"
    >

  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="8dp"
      android:text="Android Snackbar Example"
      android:textSize="24sp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintVertical_bias="0.243"
      />
  <Button
      android:id="@+id/buttonSimple"
      android:text="Normal Snackbar"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textView"
      style="@style/btnStyle"
      />
  <Button
      android:id="@+id/buttonAction"
      android:text="Snackbar with Action Button"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/buttonSimple"
      style="@style/btnStyle"
      />
  <Button
      android:id="@+id/buttonCustomView"
      android:text="Snackbar with CustomView"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/buttonAction"
      style="@style/btnStyle"
      />

</androidx.constraintlayout.widget.ConstraintLayout>
5. Move to Java source file and add below code
package com.example.snackbar;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

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

    Button simpleSnackbar = findViewById(R.id.buttonSimple);
    Button actionButtonSnackbar = findViewById(R.id.buttonAction);
    Button customViewSnackbar = findViewById(R.id.buttonCustomView);

    // Simple Snackbar code snippet
    simpleSnackbar.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {

        // Make and display Snackbar
        Snackbar.make(getView(), "Android Snackbar Example", Snackbar.LENGTH_SHORT)
            .show();
      }
    });

    actionButtonSnackbar.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        // Make and display Snackbar
        Snackbar snackbar = Snackbar.make(getView(), "Message is deleted", Snackbar.LENGTH_SHORT);
        // ADD Action Click Retry Listener
        snackbar.setAction("Undo", new UndoListener());
        // show the Snackbar
        snackbar.show();
      }
    });

    customViewSnackbar.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {

        // Make and display Snackbar
        Snackbar snackbar = Snackbar.make(getView(), "Style Text, Font and Action Color",
            Snackbar.LENGTH_SHORT);

        // Set action text color
        snackbar.setActionTextColor(
            ContextCompat.getColor(getBaseContext(), R.color.actionTextColor)
        );
        snackbar.setAction("Undo", new UndoListener());

        View snackbarView = snackbar.getView();
        TextView textView = snackbarView.findViewById(R.id.snackbar_text);
        // set no of text line
        textView.setMaxLines(2);
        //set text color
        textView.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.actionTextColor));
        //set text size
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        //Set Snackbar background color
        snackbarView.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorBg));
        snackbar.show();
      }
    });
  }

  // Define the click listener
  private class UndoListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
      // Code to undo the user's last action
      View contextView = findViewById(android.R.id.content);
      // Make and display Snackbar
      Snackbar.make(contextView, "Message restore", Snackbar.LENGTH_SHORT)
          .show();
    }
  }

  /**
   * Return the instance of View
   *
   * @return CoordinatorLayout
   */
  public View getView() {
    return findViewById(android.R.id.content);
  }
}

Conclusion

In this blog, we have learned various form implementation of Android Snackbar. I hope you enjoyed this article. Help me by sharing this post with all your friends who learning android app development.

Read our Android Architecture Components tutorial series

Leave a Reply

2000