How to dismiss a Snackbar using it's own Action button?
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()
Implement a click action and let it empty . Clicking on empty click action will dismiss snackbar .
Snackbar.make(coordinatorLayoutView, "Service Enabled", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
@Override
public void onClick(View v) {
}
})
.show();
When you use Snackbar.LENGTH_LONG
you do not need action button for dismiss , after second automatically dismiss.
You should use this code :
Snackbar snackbar = Snackbar.make(relativeLayout, "Your Message", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
snackbar.show();
Be careful this line :
Snackbar.LENGTH_INDEFINITE