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#sna
With the Material Components library you can use the snackbarStyle
attribute in your app theme:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
<item name="snackbarStyle">@style/MySnackbar</item>
</style>
with:
<style name="MySnackbar" parent="Widget.MaterialComponents.Snackbar">
<item name="android:layout_margin">32dp</item>
</style>
My solution in Kotlin extension:
fun showSnackBarWithConfirmation(text: String, view: View, action: () -> Unit) =
Snackbar.make(view, text, Snackbar.LENGTH_LONG).apply {
this.view.findViewById(R.id.snackbar_text)
.setTextColor(view.context.color(R.color.colorBackgroundLight))
this.view.setBackgroundResource(view.context.color(R.color.colorBackgroundLight))
setAction(view.context.getString(R.string.common_ok)) { action.invoke() }
(this.view.layoutParams as ViewGroup.MarginLayoutParams)
.apply { setMargins(56,0,56,300) }
show()
}
To set margin:
View viewInSnk = snkbr.getView();
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snkbr.getView().getLayoutParams();
params.setMargins(5, 5, 5, 5);
snkbr.getView().setLayoutParams(params);
and to set round corner:
viewInSnk.setBackgroundDrawable(getResources().getDrawable(R.drawable.snackbar_shape));
and for shape :
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#313131"/>
<corners android:radius="4dp"/>
</shape>
It wasn't working for me programitly, so I did it from the styles.xml
Create this style
<style name="hpr_snackbar_message_style" parent="@style/Widget.MaterialComponents.Snackbar">
<item name="android:layout_margin">@null</item>
<!-- Use default Snackbar margins for top/left/right -->
<item name="android:layout_marginTop">@dimen/mtrl_snackbar_margin</item>
<item name="android:layout_marginLeft">@dimen/snackbar_margin</item>
<item name="android:layout_marginRight">@dimen/snackbar_margin</item>
<!-- Custom bottom margin, this could work for top/left/right too -->
<item name="android:layout_marginBottom">@dimen/snackbar_margin</item>
</style>
Add it to your parent theme
<style name="parent_theme" parent="Theme.AppCompat.Light">
<item name="snackbarStyle">@style/hpr_snackbar_message_style</item>
If you want to apply margin to only specific side(s), you shall also achieve it as below. For example to apply only bottom margin,
Snackbar.make(yourContainerView, getString(R.string.your_snackbar_message), Snackbar.LENGTH_LONG_orWhateverYouWant).apply {
val params = view.layoutParams as CoordinatorLayout.LayoutParams
params.anchorId = R.id.your_anchor_id
params.anchorGravity = Gravity.TOP_orWhateverYouWant
params.gravity = Gravity.TOP_orWhateverYouWant
params.bottomMargin = 20 // in pixels
view.layoutParams = params
show()
}