Related Articles

Related Articles

Snackbar Material Design Components in Android
  • Difficulty Level : Hard
  • Last Updated : 10 Nov, 2020

The various other Material design components need special attributes to get implemented. But in this article, the Material design Snackbar is implemented and it doesn’t need the special attributes to get implemented in the application. Have a look at the following image to differentiate between the normal snack bar and Material design Snackbar in Android. What makes the Material design Snackbar is its design and easy to implement and customization. Note that we are going to implement this project using the Java language. 

Snackbar Material Design Components in Android

Steps to Implement the Material Design Snackbar

Step 1: Create an empty activity Android Studio project

Step 2: Add the required dependency

  • Add Material design dependency library to the app-level gradle file.
  • To get the app level gradle file goto Project > app > build.gradle.
  • And invoke the following dependency.

implementation ‘com.google.android.material:material:1.3.0-alpha03’



  • Refer to the following image if unable to get the app level gradle file and invoke the dependency. After invoking the dependency click on the “Sync Now” button at the top right. And make sure that the system should be connected to the network so that it can download the required files.

Step 3: Change the base application theme to the Material Components theme in the styles.xml file

  • To change the base theme of the application goto app > src > res > styles.xml and invoke the following code.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<resources>
  
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
  
</resources>

chevron_right


  • Refer to the following image if unable to locate and invoke the Material Components theme.

Step 4: Now working with the activity_main.xml file

  • Invoke the following XML code inside the activity_main.xml or can design on own.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <!--a sample button to show or popup a MDC snackbar-->
    <Button
        android:id="@+id/show_snackbar_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="128dp"
        android:layout_marginEnd="32dp"
        android:text="SHOW SNACKBAR" />
  
</LinearLayout>

chevron_right


Output UI: Run on Emulator

Snackbar Material Design Components in Android



Step 5: Now working with the MainActivity.java

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
  
public class MainActivity extends AppCompatActivity {
  
    // Button to show the snackbar
    Button bShowSnackbar;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the show snackbar button with the appropriate ID
        bShowSnackbar = findViewById(R.id.show_snackbar_button);
  
        // button click listener to show the snackbar
        bShowSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar.make(v, "You have deleted an item", Snackbar.LENGTH_LONG);
                snackbar.setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // perform any action when the button on the snackbar is clicked here in this case 
                          // it shows a simple toast
                        Toast.makeText(MainActivity.this, "The item has been restored", Toast.LENGTH_SHORT).show();
                    }
                });
                snackbar.show();
            }
        });
    }
}

chevron_right


Following output is produced:

More Functionalities of the Material design Snackbar

Functionality 1: Set the duration of the Snackbar manually

  • Invoke the following code inside the MainActivity.java.
  • In this case, the Snackbar dismiss duration is set for 3 seconds.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
  
public class MainActivity extends AppCompatActivity {
  
    // Button to show the snackbar
    Button bShowSnackbar;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the show snackbar button with the appropriate ID
        bShowSnackbar = findViewById(R.id.show_snackbar_button);
  
        // button click listener to show the snackbar
        bShowSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar.make(v, "You have deleted an item", Snackbar.LENGTH_LONG);
                snackbar.setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // perform any action when the button on the snackbar is clicked here in this case 
                          // it shows a simple toast
                        Toast.makeText(MainActivity.this, "The item has been restored", Toast.LENGTH_SHORT).show();
                    }
                });
                // the duration is in terms of milliseconds in this case its 3 seconds
                snackbar.setDuration(3000);
                snackbar.show();
            }
        });
    }
}

chevron_right


Following Output is produced:

Functionality 2: Preventing Snackbar overlap, over the FAB (Floating Action Button)

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <!--a sample button to show or popup a MDC snackbar-->
    <Button
        android:id="@+id/show_snackbar_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="128dp"
        android:layout_marginEnd="32dp"
        android:text="SHOW SNACKBAR"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
    <!--a simple floating action button with icon-->
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:backgroundTint="@color/colorPrimary"
        android:src="@drawable/ic_add_black_24dp"
        app:layout_constraintBottom_toTopOf="@+id/snackbar_layout"
        app:layout_constraintEnd_toEndOf="parent" />
  
    <!--this layout makes the floating action button to raise up 
        whenever the snackbar pops up from bottom-->
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/snackbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        app:layout_constraintBottom_toBottomOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

chevron_right


  • Now working with the MainActivity.java file to handle the overlapping of the Snackbar.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
  
public class MainActivity extends AppCompatActivity {
  
    // Button to show the snackbar
    Button bShowSnackbar;
  
    // coordinator layout for snackbar
    CoordinatorLayout mSnackbarLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the show snackbar button with the appropriate ID
        bShowSnackbar = findViewById(R.id.show_snackbar_button);
  
        // register the coordinator layout with the appropriate ID
        mSnackbarLayout = findViewById(R.id.snackbar_layout);
  
        // button click listener to show the snackbar
        bShowSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // pass the mSnackbarLayout as the view to the "make" function
                Snackbar snackbar = Snackbar.make(mSnackbarLayout, "You have deleted an item", Snackbar.LENGTH_LONG);
                snackbar.setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // perform any action when the button on the snackbar is clicked
                        // here in this case it shows a simple toast
                        Toast.makeText(MainActivity.this, "The item has been restored", Toast.LENGTH_SHORT).show();
                    }
                });
                // the duration is in terms of milliseconds
                snackbar.setDuration(3000);
                snackbar.show();
            }
        });
    }
}

chevron_right


Output: Run on Emulator

Functionality 3: Swipe feature for Snackbar to dismiss it

  • Invoke the following code inside the activity_main.xml

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <!--a sample button to show or popup a MDC snackbar-->
    <Button
        android:id="@+id/show_snackbar_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="128dp"
        android:layout_marginEnd="32dp"
        android:text="SHOW SNACKBAR"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
    <!--this layout makes the floating action button to 
        raise up whenever the snackbar pops up from bottom-->
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/snackbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        app:layout_constraintBottom_toBottomOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

chevron_right


  • Now working with the MainActivity.java file and while building the Snackbar make sure to pass the coordinator layout for the “make” function.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
  
public class MainActivity extends AppCompatActivity {
  
    // Button to show the snackbar
    Button bShowSnackbar;
  
    // coordinator layout for snackbar
    CoordinatorLayout mSnackbarLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the show snackbar button with the
        // appropriate ID
        bShowSnackbar = findViewById(R.id.show_snackbar_button);
  
        // register the coordinator layout with the
        // appropriate ID
        mSnackbarLayout = findViewById(R.id.snackbar_layout);
  
        // button click listener to show the snackbar
        bShowSnackbar.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // pass the mSnackbarLayout as the view
                        // to the make function
                        Snackbar snackbar = Snackbar.make(mSnackbarLayout, "You have deleted an item", Snackbar.LENGTH_LONG);
                        snackbar.setAction("UNDO", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // perform any action when the button on the snackbar is clicked here in this
                                // case it shows a simple toast
                                Toast.makeText(MainActivity.this, "The item has been restored", Toast.LENGTH_SHORT).show();
                            }
                        });
                        // the duration is in terms of milliseconds
                        snackbar.setDuration(3000);
                        snackbar.show();
                    }
                });
    }
}

chevron_right


Output: Run on Emulator


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :