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();
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
}