Search code examples
androidandroid-custom-viewandroid-buttonandroid-custom-drawable

Height mismatch for Normal Button and Custom Background Button in Android


I tried to set different background color for button. But the height will differs when compared to Normal and Custom Button.

enter image description here

layout file:

    <Button
        android:id="@+id/btn_normal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Normal" />

    <Button
        android:id="@+id/btn_custon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_background"
        android:layout_toEndOf="@id/btn_normal"
        android:text="Custom"
        android:textColor="#FFFFFF" />

custom_bbackground.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape >
            <corners android:radius="6dp" />
            <solid android:color="#026267"/>
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <corners android:radius="6dp" />
            <solid android:color="#026267"/>
        </shape>
    </item>
    <item >
        <shape >
            <corners android:radius="6dp" />
            <solid android:color="#026267" />
        </shape>
    </item>
</selector>

Solution

  • With the new release v23.0.0 of the AppCompat library it is now possible to create Material Design Buttons for Lollipop and Pre-Lollipop devices.

    If you just want to define the color of all Buttons you can set a special theme property called colorButtonNormal:

    Add this line to your parent theme under styles.xml

    <item name="colorButtonNormal">@color/yourColor</item>
    

    for more information refer this

    EDIT:

    Making custom theme for button will do the trick.

    <style name="CustomTheme" parent="Widget.AppCompat.Button.Colored">
        <item name="colorButtonNormal">@color/yourcolor</item>
    </style>
    

    and in use this like.

    <Button android:theme="@style/CustomTheme"/>
    

    Note: make sure you are using Widget.AppCompat.Button.Colored as parent.

    Happy Coding..