How to prevent Android Snackbar from dismissing on setAction onclick, Thanks
Snackbar.make(rootlayout, "Hello SnackBar!", Snackbar.LENGTH_INDEFINITE)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Snackbar should not dismiss
}
})
.show();
setAction("Dismiss", new View. OnClickListener() { @Override public void onClick(View v) { } }). show(); The snackbar can be dismissed by a swipe.
You can hide the current SnackBar before the end of its duration by using: ScaffoldMessenger. of(ctx). hideCurrentSnackBar();
use dismiss() to close a snackbar programatically.
Snackbar in android is a new widget introduced with the Material Design library as a replacement of a Toast. Android Snackbar is light-weight widget and they are used to show messages in the bottom of the application with swiping enabled. Snackbar android widget may contain an optional action button.
Here is a somewhat cleaner solution for achieving this, which doesn't require reflection. It's based on knowning the view ID of the button within the Snackbar. This is working with version 27.1.1 of the support library, but may no longer work in a future version if the view ID will be changed!
First, set your snackbar action using an empty OnClickListener:
snackbar.setAction("Save", new View.OnClickListener() {
@Override
public void onClick(View v) {}
});
Afterwards, add a callback to the snackbar (before showing it). Override the onShown function, find the button using R.id.snackbar_action
and add your own OnClickListener to it. The snackbar will only be dismissed when manually calling snackbar.dismiss()
, or by swiping if the snackbar is attached to a CoordinatorLayout (how to disable the swipe is a different SO question).
snackbar.addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
@Override
public void onShown(Snackbar transientBottomBar) {
super.onShown(transientBottomBar);
transientBottomBar.getView().findViewById(R.id.snackbar_action).setOnClickListener(new View.OnClickListener() {
// your code here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With