Add margins to Snackbar view

AndroidEnthusiast picture AndroidEnthusiast · Jul 20, 2015 · Viewed 18.5k times · Source

I'm updating my current app to use snackbars, in the Google spec they show various ways of using them http://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs

Example A:

Snackbar with margin

Example B:

Snackbar pinned to layout

Here's my code atm:

Snackbar snackbar = Snackbar.make(mParentLayout, displayMessage,     
    Snackbar.LENGTH_LONG);
    snackbar.setAction(actionMessage, mClickListener);
    snackbar.show();

I get the result in Example B,

How can i add margins?

Answer

BamsBamx picture BamsBamx · Jan 17, 2016

In addition to Saeid's answer, you can get the default SnackBar layout params and modify them as you want:

public static void displaySnackBarWithBottomMargin(Snackbar snackbar, int sideMargin, int marginBottom) {
    final View snackBarView = snackbar.getView();
    final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackBarView.getLayoutParams();

    params.setMargins(params.leftMargin + sideMargin,
                params.topMargin,
                params.rightMargin + sideMargin,
                params.bottomMargin + marginBottom);

    snackBarView.setLayoutParams(params);
    snackbar.show();
}