Android 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
相关产品推荐
相关产品推荐

