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

Android开发如何设置TextView截断优先级 优先截断右侧再截断左侧

解决方案

调整两个TextView的宽度配置、增加对应约束属性即可实现需求,修改后的完整布局代码如下:

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:padding="20dp">

<TextView
    android:id="@+id/leftTv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxLines="1"
    android:textColor="#333333"
    android:textSize="18sp"
    app:layout_constrainedWidth="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/rightTv"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Hello there I am a very very very very long text"
    tools:text="Hello there I am a very very very very long text" />

<TextView
    android:id="@+id/rightTv"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:minWidth="40dp"
    android:textColor="#21b38a"
    android:textSize="16sp"
    android:ellipsize="end"
    android:maxLines="1"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/leftTv"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Hello there I am a very very very very long text"
    tools:text="Hello there I am a very very very very long text" />

</androidx.constraintlayout.widget.ConstraintLayout>

核心修改说明

  • 左侧TextView将layout_width改为wrap_content,新增app:layout_constrainedWidth="true",保证它优先尽可能展示完整文本,同时不会突破约束超出父布局
  • 右侧TextView保留layout_width="0dp",新增android:minWidth属性(可根据业务调整数值,示例40dp刚好可容纳3个字符+省略号),限定它被压缩的最小阈值
  • 移除原布局中不必要的app:layout_constraintHorizontal_chainStyle、app:layout_constraintHorizontal_bias配置,避免两个控件平分可用空间

调整后会优先压缩截断右侧TextView直到它达到你设置的最小宽度,之后再开始压缩截断左侧TextView,完全符合需求的优先级逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:54:03