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

时间:2017-07-26 21:29:03

标签: android xml button font-size

我知道这听起来很简单,但我想改变一个按钮的字体大小来填充Button。即使文本没有占据按钮内部的所有空间,当我降低文本高度时,例如Button的高度也会降低。有什么方法可以更改文本大小,以便它填充Button内的空间,或者我只需要使用图像按钮。

情况如下: -

enter image description here

        <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作为我的按钮的背景第二个按钮的大小随其字体大小而变化我只希望它的大小与第一个按钮保持相同但文本大小更小。

2 个答案:

答案 0 :(得分:4)

更新

你的第二个按钮实际上并不小,它只是以你不一定期望的方式对齐。

水平LinearLayoutTextView(或子类,其中Button是)子项将“基线对齐”子项。这意味着他们将确保行中所有文本的下边缘处于相同的高度。由于您的第二个按钮使用较小的文本,因此文本底部的位于按钮内,因此LinearLayout会强制整个按钮向下调整。

将此属性添加到LinearLayout

android:baselineAligned="false"

原始

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

至于为什么文本“不占用所有空间”,这是因为Button自动填充了内置填充。您可以通过定义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>

enter image description here

答案 1 :(得分:0)

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

f对您的设计不起作用,请考虑在Button的顶部覆盖TextView(使用ConstraintLayout或FrameLayout或RelativeLayout)。之后,您可以将TextView的focusable,focusableInTouchMode和可点击属性设置为false,以便它不会拦截Button的点击。

相关问题