在 XML 中,按钮大小随其字体大小而变化

In XML Button size changes with its Font size

我知道这听起来很简单,但我想更改按钮的字体大小以填充 Button 。即使当我降低文本高度时文本并没有占用按钮内的所有 space 例如按钮的高度随着 well.Is 而降低,我可以通过任何方式更改文本大小,以便它填充按钮内的 space 或者我是否必须只使用图像按钮。

情况是这样的:-

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@android:color/black"
        android:id="@+id/led"
        >


         <Button
            android:id="@+id/grow"
            android:layout_width="match_parent"
            android:layout_height="39dp"
            android:layout_marginRight="1dp"
            android:layout_weight="1"
            android:textSize="15dp"
            android:background="@color/Lightbrown"
            android:text="A▲"

            android:textAllCaps="false"
         />

        <Button
            android:layout_width="match_parent"
            android:layout_height="39dp"
            android:text="A▼"
            android:textAllCaps="false"
            android:id="@+id/shrink"
            android:background="@color/Lightbrown"
            android:layout_marginRight="1dp"
            android:layout_weight="1"
            android:padding="0dp"
            android:textSize="10dp"

            />

看到我使用我的 Linearlayout 作为我的按钮的背景第二个按钮的大小随着它的字体大小而变化我只希望它的大小与第一个按钮保持相同但文本大小更小。

更新

您的第二个按钮实际上并没有变小,它只是以您未必期望的方式对齐。

具有 TextView(或 Button 的子类)的水平 LinearLayout 子级将 "baseline align" 子级。这意味着他们将确保行中所有文本的底部边缘处于相同的高度。由于您的第二个按钮使用较小的文本,文本底部 在按钮内部更高,因此 LinearLayout 强制 整个按钮 下来容纳。

将此属性添加到您的 LinearLayout:

android:baselineAligned="false"

原创

首先,我假设您使用的是 android:layout_height="wrap_content"。如果您不希望按钮的高度随字体大小而变化,则必须将其更改为某个固定值(或者 match_parent 如果您希望它与父按钮的大小相同)。

至于为什么文本 "doesn't take up all the space",那是因为 Buttons 有自动内置的填充。您可以通过定义 android:padding="0dp"

来删除此填充

但是,您很快就会注意到,如果您不给按钮填充任何内边距和太大的文本,它看起来真的很糟糕。具体怎么解决就看你设计的要求了

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="32dp"
        android:layout_gravity="center_horizontal"
        android:padding="0dp"
        android:textSize="36sp"
        android:text="Hello world"/>

</FrameLayout>

为您的按钮使用固定大小而不是 wrap_content

如果这对您的设计不起作用,请考虑在您的 Button 顶部叠加一个 TextView(使用 ConstraintLayout 或 FrameLayout 或 RelativeLayout)。之后,您可以将 TextView 的 focusable、focusableInTouchMode 和 clickable 属性设置为 false,这样它就不会拦截您的 Button 的点击。