Create Custom Snackbar in Android App
In order to show some feedback to the user, we can use different methods in android such as showing a toast in android, a snack bar, or a dialog box, etc. So in this tutorial, we will use Snackbar to show some message to the user.
Snackbar is used in many apps such as YouTube (when there is no internet connection and YouTube shows us a message to view the downloaded content), Google photos (when we upload any image to google photos), Google drive (when we want to delete some file), etc. Here is an example of it:
What is a Snackbar?
Snackbar is a lightweight widget that we can use as an alternative to Toast (in some cases toast is more useful than snackbar, but it depends from project to project). Snackbar is used to show messages to the user at the bottom of the app screen. Snackbar also contains an optional action button.
To implement Snackbar in our android app, we will be using the Material library.
Snackbar has mainly 3 parts as shown below:
-
Text label: It contains a single line text or multiline text (up to 2 lines) for mobile and tablets.
-
Container: Snackbars are displayed in a rectangular container with a default grey background. The containers should be completely opaque, so that the text label will remain visible to the user.
-
Action Button: This is optional, we can also use it to hide or dismiss the snackbar. If the text label is long, the action button will be displayed in the third line. We have to use different colors for the action button and a text label so that the user can differentiate between both.
Difference between Toast and Snackbar
Here are a few main points of difference between Toast and Snackbar:
Toast |
Snackbar |
Toast is shown at the center bottom of the screen. |
Snackbar is also shown at the bottom of the screen. |
Toast can be customized to be shown anywhere in the screen. |
Snackbar can not be customized to be shown anywhere in the screen, It is only shown at the bottom of the screen |
Toast message does not have any action button for recording user feedback |
Snackbar has an optional action button but only one action button is supported. |
A toast message will be shown until its time is finished (Duration variables for Toast are: Length.Long and Length.Short ) |
Snackbar can be dismissed before time by user using a swipe or using the action button or using the Java code. |
How to Set Duration of Snackbar?
Following are the constants that can be used to set the duration of the Snackbar:
-
LENGTH_INDEFINITE: It shows the Snackbar for an infinite time until it's dismissed by the user or another Snackbar is added.
-
LENGTH_LONG: It shows the Snackbar for a long time (10 seconds).
-
LENGTH_SHORT: It shows the Snackbar for short time (4 seconds).
Some Important Methods for Snackbar:
Following are some useful methods of Snackbar:
Method |
Description |
void dismiss() |
It dismisses the Snackbar and returns nothing. |
int getDuration() |
It returns the duration of Snackbar. |
boolean isShown() |
It is used to check whether Snackbar is shown or not. It will return true if snackbar is shown to the user else return false. |
make() |
It is used to make a Snackbar, and it has 3 parameters:
Syntax:
make (View view, CharSequence text, int duration);
Example:
make(constraintLayout, " some text ", Snackbar.LENGTH_SHORT);
|
setAction() |
It is used to set the action button in snackbar, it takes 2 parameters:
Syntax:
setAction(CharSequence text, View.OnClickListener listener);
Example:
setAction("Yes", new View.OnClickListener() {
@Override
public void onClick(View view) {
// define what to do on click
}
});
|
setActionTextColor() |
It is used to set the text color of action, it takes only 1 parameter:
Syntax:
setActionTextColor(int color);
// or
setActionTextColor(ColorStateList colors);
Example:
setActionTextColor(Color.GREEN);
|
setBackgroundTint() |
It is used to set the tint color of the background of the Snackbar, it also takes 1 parameter:
Syntax:
setBackgroundTint(int color);
// or
setBackgroundTint(ColorStateList colors);
Example:
setBackgroundTint(Color.RED);
|
setText() |
It is used set the text of the Snackbar, it also takes only one parameter:
- Character Sequence or
resId
Syntax:
setText(CharSequence text);
// or
setText(int resId);
Example:
setText("hello world it is a simple snackbar");
|
setTextColor() |
It is used set the text Color of the snackbar, it also takes only one parameter:
Syntax:
setTextColor(int color);
// or
setTextColor(ColorStateList colors);
Example:
setTextColor(Color.BLUE);
|
void show() |
It is used to show the Snackbar. It returns nothing and has no argument. |
So we have learned some basics about Snackbar, now it is time to add this amazing feature in our android app. We have to follow some basic steps to add snackbar in our app as shown below.
Step 1: Create a new Project
-
Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to setup Android Studio and create your first Android project)
-
Choose "Empty Activity" from the project template window and click on Next.
-
Enter the App Name, Package name, save location, language(Java/Kotlin, we will use Java for this tutorial), and the minimum SDK(we are using API 19: Android 4.4 (KitKat))
-
Next click on Finish button after filling in the above details.
-
Now, wait for the project to finish building.
Step 2: Adding the Material dependency
To show the SnackBar in our app we have to implement the Material library in our app, to do so follow the below steps.
Go to Gradle Scripts -> build.gradle (Module: app) section and import below dependencies and click the "sync Now" show at the top:
dependencies {
// Adding the material library to add snackBar in our app
implementation 'com.google.android.material:material:1.0.0'
}
Step 3: Modify activity_main.xml
Now go to app -> res -> layout -> activity_main.xml and add a LinearLayout with orientation vertical and inside LinearLayout we add different buttons for different types of snackbar. Now our activity_main.xml file will look like as shown below
<?xml version = "1.0" encoding = "utf-8" ?>
<androidx.constraintlayout.widget.ConstraintLayout
android:id = "@+id/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">
<!-- simple linear layout containing different button -->
<LinearLayout
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
<!-- button with single line snackbar -->
<Button
android:id = "@+id/snackBar1"
android:textAllCaps = "true"
android:textStyle = "bold"
android:textSize = "16dp"
android:background = "@color/colorPrimary"
android:textColor = "#ffffff"
android:text = "Simple Single Line Snackbar "
android:layout_margin = "16dp"
android:layout_width = "match_parent"
android:layout_height = "80dp"/>
<!-- button with multi line snackbar -->
<Button
android:id = "@+id/snackBar2"
android:textAllCaps = "true"
android:textStyle = "bold"
android:textSize = "16dp"
android:background = "@color/colorPrimary"
android:textColor = "#ffffff"
android:text = "Simple Multiple Line Snackbar "
android:layout_margin = "16dp"
android:layout_width = "match_parent"
android:layout_height = "80dp"/>
<!-- button with single line snackbar with action button -->
<Button
android:id = "@+id/snackBar3"
android:textAllCaps = "true"
android:textStyle = "bold"
android:textSize = "16dp"
android:background = "@color/colorPrimary"
android:textColor = "#ffffff"
android:text = "Single line Snackbar With Action Button "
android:layout_margin = "16dp"
android:layout_width = "match_parent"
android:layout_height = "80dp"/>
<!-- button with multiline snackbar with action button -->
<Button
android:id = "@+id/snackBar4"
android:textAllCaps = "true"
android:textStyle = "bold"
android:textSize = "16dp"
android:background = "@color/colorPrimary"
android:textColor = "#ffffff"
android:text = "MultiLine line Snackbar With Action Button "
android:layout_margin = "16dp"
android:layout_width = "match_parent"
android:layout_height = "80dp"/>
<!-- button with custom snackbar with action button -->
<Button
android:id = "@+id/snackBar5"
android:textAllCaps = "true"
android:textStyle = "bold"
android:textSize = "16dp"
android:background = "@color/colorPrimary"
android:textColor = "#ffffff"
android:text = "Custom Snackbar With Action Button"
android:layout_margin = "16dp"
android:layout_width = "match_parent"
android:layout_height = "80dp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Now our App UI will look like as shown below:
Step 4: MainActivity.java file
This is the main part to add snackbar in our app, first we open the MainActivity.java file and import some basic classes as shown below:
//import the basic library
import com.google.android.material.snackbar.Snackbar;
import android.graphics.Color;
import android.os.Bundle ;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
Next, we create the objects of Android Button inside MainActivity class as shown below:
//creating 5 different object of Button class
private Button b1, b2, b3, b4, b5;
Now we create different methods to show different types and styles of Snackbar as shown below:
private void showSnackBarSingleLine() {
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
Snackbar snackbar = Snackbar.make(constraintLayout, "SnackBar Single Line", Snackbar.LENGTH_SHORT);
snackbar.show();
}
private void showSnackBarMultipleLine() {
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
Snackbar snackbar = Snackbar.make(constraintLayout, "SnackBar Multiple Line with some text so that the example is completed ", Snackbar.LENGTH_SHORT);
snackbar.show();
}
private void showSnackBarSingleLineWithActionButton() {
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
Snackbar snackbar = Snackbar.make(constraintLayout, "Want to delete file", Snackbar.LENGTH_SHORT);
snackbar.setAction("Yes", new View.OnClickListener() {@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Your file is deleted ", Toast.LENGTH_SHORT).show();
}
});
snackbar.show();
}
private void showSnackBarMultipleLineWithActionButton() {
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
Snackbar snackbar = Snackbar.make(constraintLayout, "Are you sure Wanted to delete the file , it is a simple multiple line snackBar ", Snackbar.LENGTH_SHORT);
snackbar.setAction("Yes", new View.OnClickListener() {@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Your file is deleted ", Toast.LENGTH_SHORT).show();
}
});
snackbar.show();
}
private void showCustomSnackBar() {
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
Snackbar snackbar = Snackbar.make(constraintLayout, "You are not connected to internet ", Snackbar.LENGTH_LONG).setAction("RETRY", new View.OnClickListener() {@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Waiting for connection ", Toast.LENGTH_SHORT).show();
}
});
//setting action text color o red
snackbar.setActionTextColor(Color.RED);
View sbView = snackbar.getView();
//getting the textview of the snackbar
TextView textView = (TextView) sbView.findViewById(com.google.android.material.R.id.snackbar_text);
//setting snackbar text color to green
textView.setTextColor(Color.GREEN);
snackbar.show();
}
Now inside the onCreate()
method, we initialize the Button and add the OnClick Listener and call the respective method inside onClick()
:
b1 = (Button) findViewById(R.id.snackBar1);
b2 = (Button) findViewById(R.id.snackBar2);
b3 = (Button) findViewById(R.id.snackBar3);
b4 = (Button) findViewById(R.id.snackBar4);
b5 = (Button) findViewById(R.id.snackBar5);
b1.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
showSnackBarSingleLine();
}
});
b2.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
showSnackBarMultipleLine();
}
});
b3.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
showSnackBarSingleLineWithActionButton();
}
});
b4.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
showSnackBarMultipleLineWithActionButton();
}
});
b5.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
showCustomSnackBar();
}
});
Once you have added all the above code in your Main activity, then we are ready to run our app.
Output Screen for Snackbar:
In the below snapshots, you can see how the SnackBar will look in the android application.
Simple Single Line Snackbar:
Simple Multi Line Snackbar:
Simple Single Line Snackbar with Action Button:
Simple Multi Line Snackbar with Action Button:
Custom Snackbar with Action Button:
In this tutorial, we learned how to add a Snackbar to our Android App using the material library. We learned how to write the code to show Snackbar in Android app and how to add various functions to it.