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

Android LinearLayout 平均分配子項空間:layout_weight 實現 Toolbar 按鈕均分

     編輯:程式設計綜合問答

需求

水平 LinearLayout 作為 Toolbar,包含 3 個按鈕(Reply、RT、DM),要求按鈕等寬均分佔滿寬度。

核心屬性:layout_weight

  • android:layout_width="0dp" (或 match_parent 配合 weight)
  • android:layout_weight="1" 每個按鈕權重相同
  • 父容器 android:orientation="horizontal"

XML 實現

<LinearLayout
    android:id="@+id/toolbarLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/solid_yellow"
    android:orientation="horizontal"
    android:padding="5dp" > <!-- 整體內邊距 -->

    <Button
        android:id="@+id/replyButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Reply" />

    <Button
        android:id="@+id/rtButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="RT" />

    <Button
        android:id="@+id/dmButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="DM" />

</LinearLayout>

代碼動態創建

LinearLayout toolbar = new LinearLayout(this);
toolbar.setOrientation(LinearLayout.HORIZONTAL);
toolbar.setLayoutParams(new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT,
    LinearLayout.LayoutParams.WRAP_CONTENT));
toolbar.setPadding(dp(5), dp(5), dp(5), dp(5));

String[] titles = {"Reply", "RT", "DM"};
for (String title : titles) {
    Button btn = new Button(this);
    btn.setText(title);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
        0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f); // width=0, weight=1
    btn.setLayoutParams(lp);
    toolbar.addView(btn);
}

進階:按鈕間距處理

若需按鈕間固定間距,不建議用 layout_margin(會破壞均分),改用:

  • 父容器 android:divider="@drawable/divider" + android:showDividers="middle" (API 14+)
  • 或在按鈕間插入固定寬度 View (width=10dp, weight=0)

避坑指南

  • layout_width="wrap_content" + layout_weight 會導致按鈕寬度不均(先 wrap 再分配剩餘),必須 0dp。
  • 垂直 LinearLayout 同理:layout_height="0dp" + layout_weight。
  • NestedScrollView 嵌套 LinearLayout 時,子項 layout_weight 需父容器 android:fillViewport="true"。

layout_weight 是 LinearLayout 實現彈性佈局的核心,Toolbar 按鈕均分是經典應用場景,掌握「寬度 0dp + 權重 1」模式即可通吃。

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