Hafez Divandari
Hafez Divandari

Reputation: 9029

How to dismiss a Snackbar when user interact elsewhere?

How to dismiss a Snackbar when user interact elsewhere, like the way Gmail app dismiss Snackbars when user scrolls, clicks elsewhere, leaves the activity etc.

This behavior has also been mentioned in Material Design:

enter image description here

Upvotes: 1

Views: 5747

Answers (2)

joe_deniable
joe_deniable

Reputation: 2572

Maybe override dispatchTouchEvent in Activity.

private Snackbar mSnackbar;

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        if (mSnackbar != null && mSnackbar.isShown()) {

                Rect sRect = new Rect();
                mSnackbar.getView().getHitRect(sRect);

                //This way the snackbar will only be dismissed if
                //the user clicks outside it.
                if (!sRect.contains((int)ev.getX(), (int)ev.getY())) {
                    mSnackbar.dismiss();
                    mSnackbar == null;
                }
        }
    }

    return super.dispatchTouchEvent(ev);
}

Thanks to Eme's and gicci's comments for improvement to this. (I haven't tested this new slightly edited verstion).

Upvotes: 7

Mor Paz
Mor Paz

Reputation: 2223

As the guidelines that you provided in your question state:

or user interaction elsewhere (such as summoning a new surface or activity)

It does not mention anything regarding swipes or clicks while the snackbar is displayed.

In other words, so long as the user remains on the same activity the snackbar should just disappear on it's own after a timeout or if the user delibaretly swipes it off.

Also, I checked Google's Gmail app and the snackbars don't disappear if the user swipes on the same screen.

Upvotes: 1

Related Questions