Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss a Snackbar using it's own Action button?

Android design support library now includes support for Snackbar.

I've used the following code to create one:

Snackbar.make(findViewById(R.id.root_layout), result, Snackbar.LENGTH_LONG)         .setAction("Dismiss", new View.OnClickListener() {             @Override             public void onClick(View v) {              }         }).show(); 

The snackbar can be dismissed by a swipe. However, I also want to dismiss it using its own Action Button (created using the setAction function).

However there doesn't seem to be any function available that can do that.

like image 712
Asim Avatar asked Jun 09 '15 10:06

Asim


1 Answers

For Java,

The .make method returns a Snackbar object. Save an instance of that object by making it final. Then, in the onClick(), call .dismiss:

final Snackbar snackBar = Snackbar.make(findViewById(android.R.id.content), "Snackbar Message", Snackbar.LENGTH_LONG);          snackBar.setAction("Action Message", new View.OnClickListener() {             @Override             public void onClick(View v) {                 // Call your action method here                 snackBar.dismiss();             }         });         snackBar.show(); 

For Kotlin,

        Snackbar.make(             findViewById(android.R.id.content),             "Snackbar Message",             Snackbar.LENGTH_INDEFINITE         ).setAction("Action Message") {             // Call action functions here         }.show() 
like image 78
EE66 Avatar answered Sep 23 '22 17:09

EE66