Skip to content Skip to sidebar Skip to footer

In Xml Button Size Changes With Its Font Size

I know this sounds simple but I wanted to change a button's font size to fill the Button .Even though the text doesn't take all the space inside the button when I decrease text hei

Solution 1:

Update

Your second button is not actually smaller, it is just aligned in a way you wouldn't necessarily expect.

Horizontal LinearLayouts with TextView (or subclass, which Button is) children will "baseline align" the children. That means they will make sure that the bottom edge of all the text in the row is at the same height. Since your second button uses smaller text, the text bottom would be higher up inside the button, so the LinearLayout forces the whole button down to accomodate.

Add this attribute to your LinearLayout:

android:baselineAligned="false"

Original

First, I assume you're using android:layout_height="wrap_content". If you don't want your button's height to scale with font size, you'll have to change this to some fixed value (or match_parent if you want it to be the same size as its parent).

As for why the text "doesn't take up all the space", that's because Buttons have padding built into them automatically. You can remove this padding by defining android:padding="0dp"

However, you'll soon notice that the button looks really bad if you give it no padding and too-large text. How to solve that is really up to the requirements of your design.

<?xml version="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid:layout_width="wrap_content"android:layout_height="32dp"android:layout_gravity="center_horizontal"android:padding="0dp"android:textSize="36sp"android:text="Hello world"/></FrameLayout>

enter image description here

Solution 2:

Use a fixed size instead of wrap_content for your button.

f that doesn't work for your design, consider overlaying a TextView on top of your Button (with ConstraintLayout or FrameLayout or RelativeLayout). After that, you can set the TextView's focusable, focusableInTouchMode, and clickable properties to false so that it doesn't intercept your Button's clicks.

Post a Comment for "In Xml Button Size Changes With Its Font Size"