簡體   English   中英

在XML中,按鈕大小隨其字體大小而變化

[英]In XML Button size changes with its Font size

我知道這聽起來很簡單,但是我想更改按鈕的字體大小以填充按鈕。即使當我減小文本高度時文本並沒有占據按鈕內部的所有空間,例如按鈕的高度也減小了。我可以更改文本大小的方式,以使其填充Button內部的空間,或者我只需要使用Image Button即可。

情況是這樣的:

在此處輸入圖片說明

        <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用作Button的背景,第二個按鈕的大小隨其字體大小而改變,我只希望其大小與第一個Button保持相同,但使用較小的textsize。

更新

您的第二個按鈕實際上並不小,只是以您不一定期望的方式對齊。

具有TextView (或子類, Button是)子級的Horizo​​ntal LinearLayout可以使這些子級“基線對齊”。 這意味着他們將確保該行中所有文本的底邊處於相同的高度。 由於第二個按鈕使用的是較小的文本,因此文本底部在該按鈕內的位置更高,因此LinearLayout強制整個按鈕向下適應。

將此屬性添加到您的LinearLayout

android:baselineAligned="false"

原版的

首先,假設您使用的是android:layout_height="wrap_content" 如果您不希望按鈕的高度與字體大小成比例,則必須將其更改為某個固定值(如果希望與父match_parent大小相同,則將其更改為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>

在此處輸入圖片說明

為按鈕使用固定大小而不是wrap_content

如果對您的設計不起作用,請考慮將TextView覆蓋在Button頂部(使用ConstraintLayout或FrameLayout或RelativeLayout)。 之后,您可以將TextView的focusable,focusableInTouchMode和clickable屬性設置為false,以使其不會攔截Button的單擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM