Android布局实现:左右视图等宽取最大值,中间标题居中可省略
可行解决方案:ConstraintLayout 精准配置
核心是利用ConstraintLayout的约束宽度与水平偏移属性,配合TextView的省略号设置,完全匹配你的需求:
布局代码示例
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingHorizontal="16dp"> <!-- 左侧状态描述 --> <TextView android:id="@+id/tv_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="已完成" android:textSize="14sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <!-- 中间条目标题 --> <TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是一个很长很长很长很长很长很长的条目标题" android:textSize="16sp" android:maxLines="1" android:ellipsize="end" app:layout_constrainedWidth="true" app:layout_constraintStart_toEndOf="@+id/tv_status" app:layout_constraintEnd_toStartOf="@+id/tv_deadline" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:paddingHorizontal="8dp"/> <!-- 右侧到期日期 --> <TextView android:id="@+id/tv_deadline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2024-12-31 23:59" android:textSize="14sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性说明
app:layout_constrainedWidth="true":强制标题TextView遵守左右约束,文本过长时不会挤压左右视图,而是自身收缩并显示省略号。app:layout_constraintHorizontal_bias="0.5":让标题始终保持水平居中,无论左右侧视图宽度差异多大,标题中心线与父布局中心线对齐。android:ellipsize="end"+android:maxLines="1":确保标题单行显示,文本超出可用宽度时末尾自动添加省略号。- 左右侧视图用
wrap_content:自动适配自身文本长度,2-20字符的内容都能完整显示,有空间时自动扩展宽度。
效果验证
- 短文本场景:标题居中,左右视图正常显示。
- 左右视图宽度不同:标题依然保持居中,无偏移。
- 标题超长场景:标题自动收缩至不触碰左右视图的最大宽度,显示省略号,左右视图文本完整保留。
内容的提问来源于stack exchange,提问作者Alex Mortimer
相关产品推荐
相关产品推荐

