首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 兩個 CheckBox 水平排列並等寬顯示的正確姿勢

     編輯:程式設計綜合問答

問題現象

在 LinearLayout 中放置兩個 CheckBox,期望它們水平均分寬度、文字完整顯示,但實際運行時文字被截斷或佈局不均勻。

核心解決方案:使用 layout_weight

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <CheckBox
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="選項一"
        android:gravity="center"
        android:buttonTint="@color/colorPrimary" />

    <CheckBox
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="選項二"
        android:gravity="center"
        android:buttonTint="@color/colorPrimary" />

</LinearLayout>

關鍵屬性解析

屬性值作用
layout_width0dp配合 weight 時必須設為 0,避免自身寬度干擾分配
layout_weight1兩個均為 1,表示 1:1 平分父容器剩餘寬度
gravitycenter文字在 CheckBox 內水平居中,防止偏左/偏右

常見坑點

  • 忘記設 layout_width="0dp",導致 weight 不生效或文字擠壓。
  • 父容器 orientation 未設為 horizontal。
  • 文字過長未設置 ellipsize="end" 或 singleLine="true",導致換行破壞佈局。

進階:適配不同屏幕密度

若需圖標與文字垂直排列,可將 CheckBox 替換為 RadioButton 並設置 android:button="@null" + android:drawableTop="@drawable/selector",同樣配合 weight 實現均分。

掌握 weight=1 + width=0dp 黃金組合,輕鬆搞定各類均分佈局需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved