How can I be notified when a Snackbar has dismissed itself?

Tyler Pfaff picture Tyler Pfaff · Jun 18, 2015 · Viewed 33.1k times · Source

I'm using a Snackbar from the com.android.support:design:22.2.0 library. I'm using it to undo deletions. To make my life easier, I'm going to make the UI look like things are actually deleted from the data source, and if the undo button in the snack bar is not pressed, actually perform the deletions from the data source. So, I want to know when the Snackbar is no longer visible, so it's safe to delete the items.

I can call getView() on the Snackbar, but I'm not sure what listener I should be using. I tried setOnSystemUiVisibilityChangeListener() but that didn't work, I believe it is only for the system status bar.

Additionally, Snackbar can not be extended, as it has a private constructor.

Answer

and_dev picture and_dev · Oct 12, 2015

Google design library supports Snackbar callbacks in version 23. See Snackbar docs and Callback docs. You will then get notified when the Snackbar gets dismissed (and also when shown) and also the type of dismissal if this is useful for you:

snackbar.addCallback(new Snackbar.Callback() {

    @Override
    public void onDismissed(Snackbar snackbar, int event) {
      //see Snackbar.Callback docs for event details
      ...  
    }

    @Override
    public void onShown(Snackbar snackbar) {
       ...
    }
  });