I'd like to implement the new Snackbar included in the latest Design Support Library, but the way it is offered seems counter-intuitive for my, and I assume many others', use.
When the user does an important action, I want to allow them to undo it via the Snackbar, but there seems to be no way to detect when it is dismissed to do the action. It makes sense to me to do it the following way:
- User does action.
- Show Snackbar and update UI as if the action has been completed (ie it appears that data is sent to the database, but actually isn't yet).
- If user pressed "undo," revert the UI changes. If not, when the Snackbar is dismissed, it will then send the data.
But because I don't see any accessable OnDismissListener, I would therefore have to:
- User does action.
- Send info to database immediately and update UI.
- If user presses "undo," send another call to the database to remove the just-added data and revert the UI changes.
I would really like to avoid having to make the two calls to the database, and just send one when the app knows that it's safe (the user has avoided pressing "undo"). I notice there is some implementation of this in a third-party library via an EventListener, but I'd really like to stick to the Google library.
I use custom coordinatorlayout. When Snackbar is showed then onMeasure and onMeasureChild of CoordinatorLayout are called. So I overrided these methods.
Please note that you must set ids of children of the custom coordinator layout. Because I find the view of SnackBar by id. The id of SnackBar is -1.
Implement OnSnackBarListener in your activity or fragment. When the snackbar is showed then it will call onShow. And the one is dismissed then it will call onDismiss.
This was just added in v23.
To be notified when a snackbar has been shown or dismissed, you can provide a Snackbar.Callback via
setCallback(Callback)
.Francesco's answer (here) is right, but unfortunately it only works on API > 12. I submitted a feature request to the Android Issue Tracker. You can check it here and star it if you're interested. Thanks.
Now it does
To improve Hitch.united answer
I have the same problem, but I'm providing an 'undo' for deleting data.
This is how I deal with it:
This may not work for you, since you are inserting data and you may (?) need it to be available in the database after the first action, but it will work if 'faking' the data (in the UI) is feasible. My code is not optimal, and I would call it a hack, but its the best I could find while staying within the official libraries.
My actual code is more complicated (dealing with the issue of canRemoveData not being accessible inside sub classes without being final, but this is basically how I managed to achieve what you are talking about.
Hope someone can figure out a better solution.