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

Android Kotlin LinearLayout内如何实现按钮分别左对齐和右对齐

问题原因

你当前的代码存在两个问题:

  • 给Button设置的android:gravity属性仅作用于按钮内部的文本对齐,无法控制按钮自身在父布局中的位置
  • 水平方向的LinearLayout默认会将所有子控件按书写顺序从左到右依次排列,不会自动留出空白空间将第二个按钮推到最右侧

解决方案

方案1:修改原有LinearLayout实现

在两个Button中间新增一个空白占位View,设置layout_weight="1"占满中间的剩余空间即可,修改后的代码如下:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"/>

    <!-- 空白占位View,占满中间所有剩余空间 -->
    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="How"/>
</LinearLayout>

方案2:使用官方推荐的ConstraintLayout实现(性能更优)

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/btn_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <Button
        android:id="@+id/btn_how"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="How"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:42:03