You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android LinearLayout中两个Button的间距及两端对齐问题

解决LinearLayout中Button左右对齐并添加间距的问题

直接给你修改后的布局代码,能实现左侧Button贴布局左端、右侧Button贴布局右端,中间自动填充间距的效果:

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

    <Button
        android:id="@+id/truthDialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/truthdialogbutton"
        android:text="truth" />

    <!-- 中间填充空白,把两个按钮挤到两端 -->
    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <Button
        android:id="@+id/dareDialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/daredialogbutton"
        android:text="dare" />
</LinearLayout>

关键调整点:

  • 核心问题修正:把LinearLayout的android:layout_width从wrap_content改成match_parent,只有让布局占满父容器的宽度,按钮才有空间往左右两端对齐。你之前调margin/padding没用,就是因为布局本身只包裹两个按钮,没有多余空间。
  • 中间间距实现:添加的View通过layout_weight="1"占据所有剩余空间,自动把两个按钮推到左右两端。如果想要固定宽度的间距,把这个View的layout_width改成你需要的数值(比如20dp),去掉layout_weight即可。

内容的提问来源于stack exchange,提问作者Ruru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:42:37