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

如何用ConstraintLayout实现TextView_1居中且遇TextView_2时末尾省略?

用ConstraintLayout实现居中且以指定View为边界省略的TextView

可以通过ConstraintLayout的约束属性结合TextView的省略配置实现需求,不需要通过代码动态设置内边距,纯XML就能搞定,具体方案如下:

核心思路

给目标TextView(TextView_1)设置双向约束:一边对齐父布局左侧,另一边对齐TextView_2的左侧,同时开启宽度约束,让TextView_1的最大宽度被限制在父布局左侧到TextView_2左侧的范围内;再通过水平偏移量让文本在这个范围内居中,最后配置文本省略规则。

完整XML示例

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text to be centered but ellipsize against TextView_2 when it gets longer"
        android:ellipsize="end"
        android:singleLine="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/textView2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constrainedWidth="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="TextView_2"
        android:layout_marginStart="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/textView1" />

</androidx.constraintlayout.widget.ConstraintLayout>

关键属性说明

  • app:layout_constrainedWidth="true":强制TextView_1的宽度不超出start和end约束的范围,即使文本内容过长也不会突破TextView_2的边界
  • app:layout_constraintHorizontal_bias="0.5":让TextView_1在约束的水平范围内保持居中对齐
  • android:ellipsize="end" + android:singleLine="true":文本长度超出约束范围时,自动在末尾添加省略号

这个方案完美适配TextView_2为0dp拉伸的场景,因为ConstraintLayout会在布局阶段自动计算TextView_2的实际宽度,不需要手动通过代码获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:12:02