水平 LinearLayout 作為 Toolbar,包含 3 個按鈕(Reply、RT、DM),要求按鈕等寬均分佔滿寬度。
android:layout_width="0dp" (或 match_parent 配合 weight)android:layout_weight="1" 每個按鈕權重相同android:orientation="horizontal"<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。layout_height="0dp" + layout_weight。layout_weight 需父容器 android:fillViewport="true"。layout_weight 是 LinearLayout 實現彈性佈局的核心,Toolbar 按鈕均分是經典應用場景,掌握「寬度 0dp + 權重 1」模式即可通吃。