Snackbar with CoordinatorLayout disable dismiss

无人久伴 提交于 2019-12-04 04:02:12

You can alter the duration of Snackbar to be shown. It will be similar to disable dismiss.

int     LENGTH_INDEFINITE   Show the Snackbar indefinitely. 

Check docs.

if it does not work For this then there is only one way, Implement Your custom Snackbar and override dismiss() method and in that do nothing. :) As dismiss() is a public API.

The answer about just using LENGTH_INDEFINITE is not sufficient.

It is only non-dismissable when the Snackbar is no child of CoordinatorLayout. When it is a child, you can still swipe away the SnackBar.

What you can do in that case is listen for the dismiss swipe and simply re-show the Snackbar.

public void showAnnoyingSnackBar(View root, String text) {
    Snackbar.make(root, text, Snackbar.LENGTH_INDEFINITE)
        .setCallback(new Snackbar.Callback() {
            @Override public void onDismissed(Snackbar snackbar, int event) {
                // recursively call this method again when the snackbar was dismissed through a swipe
                if (event == DISMISS_EVENT_SWIPE) showAnnoyingSnackBar(root, text);
            }
        })
        .show();
}

I noticed that when show() method is called, SnackbarLayout is not fully initialised yet.

To lock dissmiss we have to clear behavior after SnackbarLayout initialisation. the best place to do this is for example in OnPreDrawListener of SnackbarLayout

final Snackbar snack = Snackbar.make(getView(), "I can't be dissmiss", Snackbar.LENGTH_INDEFINITE);
    snack.show();
    snack.getView().getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            snack.getView().getViewTreeObserver().removeOnPreDrawListener(this);
                ((CoordinatorLayout.LayoutParams) snack.getView().getLayoutParams()).setBehavior(null);
                return true;
            }
        });

Snackbar now has actual support disabling swipe to dismiss using the setBehavior method. The great thing here is that before you would always lose some behaviors which are now preserved. You'll also want to use Snackbar.LENGTH_INDEFINITE

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

Snackbar.make(view, stringId, Snackbar.LENGTH_INDEFINITE)
    .setBehavior(new NoSwipeBehavior())
    .show();

class NoSwipeBehavior extends BaseTransientBottomBar.Behavior {

    @Override
    public boolean canSwipeDismissView(View child) {
      return false;
    }
}

I was successful in disabling the swipe-sideways-to-dismiss snackbars with the following hack (after calling snackbar.show())

((android.support.design.widget.CoordinatorLayout.LayoutParams) snackbar.getView().getLayoutParams()).setBehavior(null);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!