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

后端 未结 6 1649
执念已碎
执念已碎 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:15

    You can disable streaming touch events rather than clicks to the Snackbar view.

    mSnackBar.getView().setOnTouchListener(new View.OnTouchListener() {
                public long mInitialTime;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (v instanceof Button) return false; //Action view was touched, proceed normally.
                    else {
                        switch (MotionEventCompat.getActionMasked(event)) {
                            case MotionEvent.ACTION_DOWN: {
                                mInitialTime = System.currentTimeMillis();
                                break;
                            }
                            case MotionEvent.ACTION_UP: {
                                long clickDuration = System.currentTimeMillis() - mInitialTime;
                                if (clickDuration <= ViewConfiguration.getTapTimeout()) {
                                    return false;// click event, proceed normally
                                }
                            }
                        }
                        return true;
                    }
                });
    

    Or you could just replace the Snackbar behavior with some empty CoordinatorLayout.Behavior:

    public CouchPotatoBehavior extends CoordinatorLayout.Behavior{
    
        //override all methods and don't call super methods. 
    
    }
    

    This is the empty behavior, that does nothing. Default SwipeToDismissBehavior uses ViewDragHelper to process touch events, upon which triggers the dismissal.

     ViewGroup.LayoutParams lp = mSnackbar.getView().getLayoutParams();
     if (lp instanceof CoordinatorLayout.LayoutParams) {
         ((CoordinatorLayout.LayoutParams)lp).setBehavior(new CouchPotatoBehavior());
           mSnackbar.getView().setLayoutParams(lp);              
    }
    

提交回复
热议问题