How to use setDuration() method in SnackBar (Android Design Support Library)
Solution 1:
Based on the implementation of Snackbar
and SnackbarManager
, I can confirm Eugene H's assessment: it's a bug. From SnackbarManager
:
private void scheduleTimeoutLocked(SnackbarRecord r) {
mHandler.removeCallbacksAndMessages(r);
mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_TIMEOUT, r),
r.duration == Snackbar.LENGTH_LONG
? LONG_DURATION_MS
: SHORT_DURATION_MS);
}
So, any value that is not LENGTH_LONG
results in a short-duration snackbar.
I have filed an issue about it.
Edit: Has been fixed in revision 22.2.1. Check the release notes here
The android docs have NOT been updated yet, but if you jump into the source code you'll notice that the parameter to the method setDuration(int duration) can either be one of LENGTH_SHORT, LENGTH_LONG, LENGTH_INDEFINITE or a custom duration in milliseconds
Solution 2:
Set the initial duration to LENGTH_INDEFINITE then set your custom duration afterwards:
Snackbar
.make(parentLayout, "Feed cat?", Snackbar.LENGTH_INDEFINITE)
.setAction("Yes", snackOnClickListener)
.setActionTextColor(Color.MAGENTA)
.setDuration(8000)
.show();
EDIT
Setting a period directly in milliseconds now works;
Snackbar
.make(parentLayout, "Feed cat?", 8000)
.setAction("Yes", snackOnClickListener)
.setActionTextColor(Color.MAGENTA)
.show();
Solution 3:
Since 'com.android.support:design:22.2.1'
you can set the duration of your Snackbar to LENGTH_INDEFINITE
it will make the Snackbar shown until it is dismissed or another snackbar is shown.