'Background adding more padding to Button

I have this simple XML file in my Android Studio. There are 2 buttons

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:text="Button 2" />

</LinearLayout>

And here is the outcome

Result

The only difference in button 1 and button 2 is adding background to button 2, but the background added more padding to button 2.

Can anyone tell me why it's like that and what I can do to remove the extra padding



Solution 1:[1]

Since you are using a MaterialComponents.* theme your Button is replaced at runtime by a MaterialButton.

In the 2nd Button, using a custom background with android:background the default MaterialShapeDrawable is not used and some features like stroke, shapeappearance (rounded corners), ripple, insets are not set (since they are related to the MaterialShapeDrawable) . You have to provide them with your custom background.

Use:

<Button
    app:backgroundTint="@color/white"
    ../>

Solution 2:[2]

First replace your Button with MaterialButton then You can try add zero to insetTop and insetBottom like below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:orientation="vertical">

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

<com.google.android.material.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:insetBottom="0dp"
    android:insetTop="0dp"
    android:background="@color/white"
    android:text="Button 2" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriele Mariotti
Solution 2 Emre Tekin