Apache
Apache

Reputation: 341

MaterialButton size difference to Button

I' am setting up a new application and came across the fact that the materialButton's height does't match the size which i set. So i tried on the regular Button and as you guys can see in the screenshot below. The buttons have different height although they getting the same height as you can see in my code.

How can i get normal height with MaterialButton?

Thank you.

public class MainActivity extends AppCompatActivity {

MaterialButton materialButton;
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setId(getGeneratedId());

    setContentView(linearLayout);

    int buttonWidth = getResources().getDimensionPixelSize(R.dimen.buttonWidth);
    int buttonHeight = getResources().getDimensionPixelSize(R.dimen.buttonHeight);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(buttonWidth, buttonHeight);

    materialButton = new MaterialButton(this);
    materialButton.setId(getGeneratedId());
    materialButton.setLayoutParams(layoutParams);
    materialButton.setBackgroundColor(Color.BLUE);
    materialButton.setText("MatrialB");
    materialButton.setTextColor(Color.WHITE);


    button = new Button(this);
    button.setId(getGeneratedId());
    button.setLayoutParams(layoutParams);
    button.setBackgroundColor(Color.RED);
    button.setText("Button");
    button.setTextColor(Color.WHITE);

    linearLayout.addView(materialButton);
    linearLayout.addView(button);
    
}

Integer getGeneratedId() {
    return ViewCompat.generateViewId();
}

}

Screenshot

Upvotes: 27

Views: 14719

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364730

The MaterialButton has a default style with insetBottom and insetTop set to a value of 6dp.

You can check the difference without/with the vertical insets:

enter image description here

You can change the default with:

<com.google.android.material.button.MaterialButton
    android:insetTop="0dp"
    android:insetBottom="0dp"

or programmatically (it requires at least 1.3.0-alpha03) with:

    button.insetTop = 0
    button.insetBottom = 0

Upvotes: 29

ferini
ferini

Reputation: 1958

I believe the space on top and bottom of the MaterialButton is coming from android:insetTop/android:insetBottom which is 6dp for me with material components 1.0.0. I am not sure, how to set these programmatically, but it can be done easily in xml:

<com.google.android.material.button.MaterialButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:insetBottom="0dp"
      android:insetTop="0dp"/>

Upvotes: 59

Related Questions