How to use setDuration() method in SnackBar (Android Design Support Library)

tehnolog picture tehnolog · May 30, 2015 · Viewed 36.4k times · Source

From Documentation: parameter duration - either be one of the predefined lengths: LENGTH_SHORT, LENGTH_LONG, or a custom duration in milliseconds. But I can't set custom duration.

For example

Snackbar
    .make(parentLayout, "Feed cat?", 8000) // try here
    .setAction("Yes", snackOnClickListener)
    .setActionTextColor(Color.MAGENTA)
    .setDuration(8000) // try here
    .show();

but instead of 8 seconds Snackbar gone quickly.

Answer

CommonsWare picture CommonsWare · May 31, 2015

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