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

后端 未结 6 1666
执念已碎
执念已碎 2020-12-05 18:52

Is there a way to prevent the user from dismissing a snackbar by swiping on it?

I have an app that shows a snack bar during network login, I want to avoid it to be d

6条回答
  •  旧巷少年郎
    2020-12-05 19:28

    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 {
        @Override
        public boolean canSwipeDismissView(@NonNull View view) {
            return false;
        }
    }
    

提交回复
热议问题