How to disable snackbar's swipe-to-dismiss behavior How to disable snackbar's swipe-to-dismiss behavior android android

How to disable snackbar's swipe-to-dismiss behavior


This worked for me:

    Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();    snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);    snackbar.show();    layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {        @Override        public void onGlobalLayout() {            ViewGroup.LayoutParams lp = layout.getLayoutParams();            if (lp instanceof CoordinatorLayout.LayoutParams) {                ((CoordinatorLayout.LayoutParams) lp).setBehavior(new DisableSwipeBehavior());                layout.setLayoutParams(lp);            }            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {                layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);            } else {                //noinspection deprecation                layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);            }        }    });

Where DisableSwipeBehavior is:

public class DisableSwipeBehavior extends SwipeDismissBehavior<Snackbar.SnackbarLayout> {    @Override    public boolean canSwipeDismissView(@NonNull View view) {        return false;    }}


Snackbar now has actual support for this by using the setBehavior method. The great thing here is that before you would always lose some behaviors which are now preserved.

Note that the package moved so you have to import the "new" Snackbar in the snackbar package.

Snackbar.make(view, stringId, Snackbar.LENGTH_LONG)    .setBehavior(new NoSwipeBehavior())    .show();class NoSwipeBehavior extends BaseTransientBottomBar.Behavior {    @Override    public boolean canSwipeDismissView(View child) {      return false;    }}


This worked for me :

Snackbar snackbar = Snackbar.make(findViewById(container), R.string.offers_refreshed, Snackbar.LENGTH_LONG);    final View snackbarView = snackbar.getView();    snackbar.show();    snackbarView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {        @Override        public boolean onPreDraw() {            snackbarView.getViewTreeObserver().removeOnPreDrawListener(this);            ((CoordinatorLayout.LayoutParams) snackbarView.getLayoutParams()).setBehavior(null);            return true;        }    });

Good luck! :)