0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Use Snackbar in Android: Simple Guide with Examples

In Android, use Snackbar.make(view, message, duration) to create a snackbar and call show() to display it. You can add an action button with setAction() to let users respond to the message.
๐Ÿ“

Syntax

The basic syntax to create and show a Snackbar is:

  • Snackbar.make(view, message, duration): Creates the Snackbar attached to a view.
  • setAction(text, listener): Adds an optional action button with a click listener.
  • show(): Displays the Snackbar on screen.
java
Snackbar.make(view, "Message text", Snackbar.LENGTH_SHORT).setAction("Undo", v -> {
    // Handle action click
}).show();
Output
A small bar appears at the bottom with the message and an Undo button.
๐Ÿ’ป

Example

This example shows a button that, when clicked, displays a Snackbar with a message and an Undo action.

java
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
    Snackbar.make(v, "Item deleted", Snackbar.LENGTH_LONG)
        .setAction("Undo", view -> {
            Toast.makeText(v.getContext(), "Undo clicked", Toast.LENGTH_SHORT).show();
        })
        .show();
});
Output
When the button is tapped, a Snackbar appears at the bottom saying "Item deleted" with an Undo button. Tapping Undo shows a Toast message "Undo clicked".
โš ๏ธ

Common Pitfalls

Common mistakes when using Snackbar include:

  • Passing null or wrong view to Snackbar.make() which causes a crash or no display.
  • Not calling show() after creating the Snackbar, so it never appears.
  • Using a view that is not attached to the current layout, so Snackbar cannot find a parent.
java
/* Wrong: Passing null view */
Snackbar.make(null, "Hello", Snackbar.LENGTH_SHORT).show();

/* Right: Use a valid view from layout */
View rootView = findViewById(android.R.id.content);
Snackbar.make(rootView, "Hello", Snackbar.LENGTH_SHORT).show();
Output
Wrong code crashes; right code shows Snackbar at bottom of screen.
๐Ÿ“Š

Quick Reference

Remember these key points when using Snackbar:

  • Use a valid view from your layout as the anchor.
  • Choose duration: Snackbar.LENGTH_SHORT, Snackbar.LENGTH_LONG, or Snackbar.LENGTH_INDEFINITE.
  • Add an action with setAction() if you want user interaction.
  • Always call show() to display it.
โœ…

Key Takeaways

Use Snackbar.make(view, message, duration) and call show() to display a Snackbar.
Always pass a valid view attached to your layout to Snackbar.make().
Add user actions with setAction() for interactive messages.
Choose the right duration for your message visibility.
Never forget to call show() after creating the Snackbar.