Snackbar Material Design Components in Android
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.
Steps to Implement the Material Design Snackbar
Step 1: Create an empty activity Android Studio project
- Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio to create an Android Studio project. Note that we are going to implement this project using the Java language.
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.
- 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.
- 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.
Output UI: Run on Emulator
Step 5: Now working with the MainActivity.java
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.
Following Output is produced:
Functionality 2: Preventing Snackbar overlap, over the FAB (Floating Action Button)
- To prevent the simple overlapping of the Sncakbar refer to How To Avoid Snackbar Overlap Floating Action Button in Android?. This method shows the setting of the acnhorPoint to the Floating action button.
- Invoke the following code inside the activity_main.xml.
- Now working with the MainActivity.java file to handle the overlapping of the Snackbar.
Output: Run on Emulator
Functionality 3: Swipe feature for Snackbar to dismiss it
- Invoke the following code inside the activity_main.xml
- Now working with the MainActivity.java file and while building the Snackbar make sure to pass the coordinator layout for the “make” function.
Output: Run on Emulator