Home > OS >  How to set margin in SnackBar
How to set margin in SnackBar

Time:07-05

I'm trying to add margins at bottom, left and right to my SnackBar but I'm not able to get it.

That's what I tried:

var snackBar = Snackbar.make(binding.root,msg,Snackbar.LENGHT_LONG)
var snackbarLayout = snackBar.view. as Snackbar.SnackbarLayout
var layoutParams = snackbarLayout.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.setMargins(32,0,32,32)
snackbarLayout.layoutParams = layoutParams
snackBar.show()

I get an error in snackbarLayout.layoutParams and its this:

SnackbarBaseLayout.setLayoutParams can only be called from within the same library group

I don't know how to solve this error or if its there another way to set margins to this snackbar. Any idea?

CodePudding user response:

You can try like this, without a class cast to Snackbar.SnackbarLayout.

private fun makeSnackbar(message: String) {
    val snackbar = Snackbar.make(binding.root, message ,Snackbar.LENGHT_LONG)
    // assuming the parent / root is CoordinatorLayout
    val viewParams = snackbar.view.layoutParams as CoordinatorLayout.LayoutParams

    viewParams.setMargins(...)
    snackbar.view.layoutParams = viewParams
    snackbar.show()
}

CodePudding user response:

It is very simple to add a margin for Snackbar, you need to create a style for Snackbar and add that style to your app theme. here is an example of the same!

Create a new Style for Snackbar

<style name="SnackBarStyleName" parent="Widget.MaterialComponents.Snackbar">
    <item name="android:layout_margin">32dp</item>
</style>

Add this to your app theme which looks like this,

<style name="Theme.DemoCompactCalendar" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
     <item name="snackbarStyle">@style/SnackBarStyleName</item>
</style>

and it's done!

Note: if your app theme is a material theme then use material component otherwise use appCompact component

  • Related