4

I need to create a SnackBar that requires the user to click to dismiss. How do I do that? The following won’t compile and I don’t want to make the SnackBar variable a field.

final Snackbar snack = Snackbar.make(findViewById(R.id.notAvailable),
                "You don't have this feature",
                Snackbar.LENGTH_INDEFINITE)
                .setAction("OK", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snack.dismiss();
            }
        });
        snack.show();
Nouvel Travay
  • 6,292
  • 13
  • 40
  • 65
  • If you want to use the action button for something else, you can dismiss the Snackbar by clicking elsewhere within the Snackbar, like this: `final Snackbar snackbar = Snackbar.make(yourView, yourMainText, Snackbar.LENGTH_INDEFINITE).setAction(yourActionText, yourActionOnClickListener); View snackbarView = snackbar.getView(); snackbarView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { snackbar.dismiss(); } }); snackbar.show();` – ban-geoengineering Nov 07 '18 at 14:19

1 Answers1

5

Using the normal onClick Listener. implement a click action and let it empty, empty dismiss the sanckbar itself . Clicking on empty click action will dismiss snackbar .

Sample Code.

Snackbar.make(coordinatorLayoutView, "Service Enabled", Snackbar.LENGTH_LONG)
                        .setAction("DISMISS", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        })
                        .show();
Maheshwar Ligade
  • 6,709
  • 4
  • 42
  • 59
  • This is the correct approach to dismiss the Snackbar. However if you wish, you can have a Snackbar object and operate setAction() and show () methods on that for better understanding. – Nilesh Singh Feb 11 '16 at 19:23
  • In order to keep the snackbar visible, it also needs the LENGTH_INDEFINITE attribute (as shown in questions code). – Eric Engel Aug 08 '17 at 02:46
  • Just for the sake of completeness: it does not matter if click handler is empty or has some lines of code - it will be executed and snackbar will dismiss automatically. This also works if LENGTH_INDEFINITE. – ror Apr 05 '19 at 20:45