Search code examples
androidandroid-stylesmaterial-componentsandroid-snackbarmaterial-components-android

How to customize the style of the action button in the Snackbar


I am using the Snackbar provided by the Material Components Library.
I am looking for a way to customize the style of the ACTION Button.

enter image description here

I know that the Snackbar uses this layout (layout.mtrl_layout_snackbar_include) with this Button:

  <Button
    android:id="@+id/snackbar_action"

but I am trying to avoid to use some workarounds that can stop to work with the next releases.
In particular I would like to use a OutlinedButton style and a custom shape as an arrow.


Solution

  • With the version 1.1.0 of the Material Components Library you can define in your app theme the style used by the action button within a Snackbar using the snackbarButtonStyle attribute.

    <style name="AppTheme" parent="Theme.MaterialComponents.*">
    
        <!-- Style to use for action button within a Snackbar in this theme. -->
        <item name="snackbarButtonStyle">@style/Widget.MaterialComponents.Button.TextButton.Snackbar</item>
        ....
    </style>
    

    You can customize the style using:

      <style name="Custom.MaterialComponents.Button.TextButton.Snackbar" parent="@style/Widget.MaterialComponents.Button.TextButton.Snackbar">
        <item name="strokeColor">@color/...</item>
        <item name="strokeWidth">1dp</item>
        ....
        <item name="shapeAppearanceOverlay">@style/Snackbar.ShapeAppearanceOverlay.Arrow</item>
      </style>
    

    With the shapeAppearanceOverlay you can customize the shape:

      <style name="Snackbar.ShapeAppearanceOverlay.Button.Arrow" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerFamilyTopRight">cut</item>
        <item name="cornerFamilyBottomRight">cut</item>
    
        <item name="cornerSizeTopLeft">0dp</item>
        <item name="cornerSizeBottomLeft">0dp</item>
        <item name="cornerSizeTopRight">50%</item>
        <item name="cornerSizeBottomRight">50%</item>
      </style>
    

    enter image description here

    You can obtain an OutlinedButton style in same way. Just define a custom style with:

      <style name="Outlined.MaterialComponents.Button.TextButton.Snackbar" parent="@style/Widget.MaterialComponents.Button.OutlinedButton">
        <item name="strokeColor">@color/...</item>
        <item name="strokeWidth">1dp</item>
        <item name="android:textColor">@color/...</item>
      </style>
    

    enter image description here