Search code examples
androidandroid-layoutbuttonpaddingcentering

How to center unicode symbol as a text inside of Button in layout (android xml)?


I am creating calculator for Android. In my layout.xml file I have <LinearLayout> and a <Button> inside. I want to have a button with one-symbol text in it, which must be centered horizontally and vertically. I've succeeded to center most of text symbols, except arrows, which Unicodes are \u2190 and \u2192. Is it possible to fix the problem using paddings or android:gravity? Or there's a more complex solution?

In this screenshot you can find an example of incorrect arrows' positioning along with correct other symbols' positioning

I tried several combinations of android:textSize, 'android:paddingBottom' and 'android:paddingTop' with different values. I expect that simple 'android:paddingBottom' with certain parameter should help me but if I specify value more than 10dp, text starts to shift up, not down.

Here's my layout.xml:

<Button
   style="@style/ExtraButtonStyle"
   android:text="\u2190"
   android:textSize="44dp"
   android:paddingBottom="4dp"
   android:id="@+id/left_arrow">
</Button>

And here's my styles.xml file with applied styles:

<resources>
    <style name="MyButtonStyle">
        <item name="android:layout_width">60dp</item>
        <item name="android:layout_height">60dp</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:layout_marginLeft">12dp</item>
        <item name="android:layout_marginRight">12dp</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
        <item name="android:textSize">30dp</item>
        <item name="android:textAllCaps">false</item>
    </style>

    <style name="ExtraButtonStyle" parent="MyButtonStyle">
        <item name="android:backgroundTint">@color/grey</item>
    </style>
</resources>

Solution

  • Delete in layout.xml the line

    android:paddingBottom="4dp"
    

    and add in MainActivity after the line

    Button buttonLeftArrow = findViewById(R.id.left_arrow);
    

    the additional line

    buttonLeftArrow.setPadding(0,0,0,32);
    

    enter image description here

    EDIT: Sorry, I forgot in my first answer an important change I made to get the pictured button: Your font size 44dp is much too big for a button of size 60x60dp. Then paddingBottom no longer works as expected and creates wired effects because there is simply too little space for this font size and this paddingBottom.

    So you only have to change the following two numbers in your layout.xml:

    android:textSize="22dp"
    android:paddingBottom="15dp"
    

    If you increase the font size, the weird effects start, if you decrease it, everything works as expected.