Search code examples
androidandroid-layoutandroid-studiobuttonpadding

Change Padding on Borderless Buttons


I am developing an application, but I have run into a slight issue. I am a huge fan of the Borderless Button style (style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"), but I cannot change the padding on the buttons. Why do I need to change the padding? Because there is a minimum padding or width of the buttons that can make them look unpleasant, or just make waste space. This issue can be seen when there is very little text:

enter image description here enter image description here

The capped spacing is there one where the minimum width of the button is 'capped'. I have tried setting the padding to zero programmatically and messing with the padding in XML but nothing works. I have noticed that the AlertDialog does not have this issue as bad:

enter image description here enter image description here

You can see in the background the 'Capped' Spacing card compared to the Dialog. My question is, how can I reduce the padding myself? I would prefer not to have to write a custom style for the button.


Solution

  • One option is to apply the AlertDialog button style to your button:

    style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
    

    For a more detailed answer, the space around the text here isn't exactly padding as such. The minimum size is determined by other attributes set in the style which is why trying to tweak the padding doesn't work, padding only starts to have an effect on bigger buttons(ie. longer text).

    If we dip into the styles, it reveals a potentially useful technique to help. The AlertDialog button style looks like this:

    <!-- Alert dialog button bar button -->
    <style name="Widget.Material.Button.ButtonBar.AlertDialog" 
        parent="Widget.Material.Button.Borderless.Colored">
        <item name="minWidth">64dp</item>
        <item name="minHeight">@dimen/alert_dialog_button_bar_height</item>
    </style>
    

    So the AlertDialog button actually inherits from the Borderless.Colored style and only tweaks a couple of attributes: minWidth and minHeight.

    You could also do this, either by making your own style similar to the one above, or by setting minWidth and/or minHeight directly on the button.

    <Button
        ....
        style="@style/Widget.AppCompat.Button.Borderless.Colored"
        android:minWidth="48dp"
        android:minHeight=... />
    

    Playing around with these will hopefully get the result you're looking for, and if you go as far as setting the minWidth and minHeight to 0dp, then it becomes all about the content and the padding.