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

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.


Solution 1:

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) {
       ...
    }
  });

Solution 2:

snackbar.addCallback(new Snackbar.Callback() {

    @Override
    public void onDismissed(Snackbar snackbar, int event) {
        if (event == Snackbar.Callback.DISMISS_EVENT_TIMEOUT) {
            // Snackbar closed on its own
        }
    }

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