0

I am trying to change margin for all my buttons in application. I have defined style:

<resources>
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <item name="materialButtonStyle">@style/TempButtonStyle</item>
    </style>

    <style name="TempButtonStyle" parent="Widget.MaterialComponents.Button">
        <item name="android:layout_margin">10dp</item>
    </style>
 </resources>

but it doesn't work. If I attach this style to single button it works great:

<com.google.android.material.button.MaterialButton
        android:id="@+id/change_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/change_date"
        style="@style/TempButtonStyle"/>

Any suggestions how to change it globally?

user3921796
  • 117
  • 3
  • 13

2 Answers2

1

In-order to change margin for Material Button globally, need to use inset in the style as below

<style name="TempButtonStyle" parent="Widget.MaterialComponents.Button">
        <item name="android:insetLeft">10dp</item>
        <item name="android:insetRight">10dp</item>
        <item name="android:insetBottom">10dp</item>
        <item name="android:insetTop">10dp</item>
</style>
satuser
  • 766
  • 8
  • 17
0

I have tried to find a solution for as long as the answer has been up, but there is none. At least none if you want to define the Buttonstyle globally as you did in your question.

The problem is the following: As you probably know LayoutParams are tied to a specific ViewGroup type (like LinearLayout or FrameLayout). This causes the following problem: You have defined layout_margin in your style which is applied globally vai materialButtonStyle. However for this attribute (and any layout attribute) to be applied, the parent of the View must be known. This is why setting style="@style/TempButtonStyle" does work.

So what's the easiest way to fix it?
I know it's not ideal but extending the MaterialButton and setting margins programmatically is a way to deal with this:

Just override onMeasure and inside it do the following (after super call):

MarginLayoutParams::class.java.cast(layoutParams)?.apply {
    topMargin = 30
    bottomMargin = 30
    leftMargin = 30
    rightMargin = 30
    layoutParams = this
}

Or Java:

    MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
    margins.topMargin = 30;
    margins.bottomMargin = 30;
    margins.leftMargin = 30;
    margins.rightMargin = 30;
    setLayoutParams(margins);

(of course you don't want to use a hardcoded value and get the 10dp either from a defined dimension or using typedvalue)

Rene Ferrari
  • 4,096
  • 3
  • 22
  • 28