How to dismiss Snackbar when user does any action?

illusionJJ picture illusionJJ · Jan 24, 2016 · Viewed 10.1k times · Source

I can show snackbar like this.

Snackbar snackbar = Snackbar.make(this.findViewById(android.R.id.content), "snackbar", Snackbar.LENGTH_INDEFINITE)
        .setAction("action", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ...
            }
        });
snackbar.show();

My snackbar has indefinite length and I want it. But When user does any action, such as scrolling screen or touching screen/view, I want to dismiss snackbar. I can find some library and codes but they are so complicate. Is there not easy way to dismiss snackbar?

Answer

Eliahu Horwitz picture Eliahu Horwitz · Jan 24, 2016

I am assuming you are using fragments, so you could set an onTouchListener to your fragments main layout, and put inside snackbar.dismiss().

if you just want to dismiss on scroll set an onScrollListener and in the event dismiss the snackbar, Here's an implementation for recyclerview onScroll:

list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) 
                    snackbar.dismiss();
                    }
                });