javaandroidandroid-snackbar

How to format the text of a Snackbar in Android


I have a method that displays snackbars which is called from many different fragments. Here is the code of this method:

public static void showSnackBar(Activity activity, String message, View root) {

    int duration = 5000;
    Snackbar currentSnackBar = Snackbar.make( activity, root, message, Snackbar.LENGTH_INDEFINITE).setDuration(duration);

    View sbView = currentSnackBar.getView();
    sbView.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorBlue));

    FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)sbView.getLayoutParams();
    params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;

    sbView.setLayoutParams(params);
    currentSnackBar.setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_FADE);
    currentSnackBar.show();
}

Currently it shows the snackbar at the top center of the display. I would like to have the following formatting modifications:

  1. The textsize should be bigger
  2. The text should be aligned in the center. At the moment it is aligned to the left.

Reminder: do you know how I can do this?


Solution

  • You can access the snacker textview by doing -

     val textView =
                    sbView.findViewById<TextView>(R.id.snackbar_text)
    

    Then set whatever properties you want, to this textview