You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

TextView文本省略(ellipsize)功能异常问题排查

我来帮你搞定TextView超出指定宽度显示省略号的问题~

首先看你给出的布局代码,核心属性已经有了,但我帮你梳理下更清晰的实现方式和避坑点:

核心生效属性说明

要实现单行文本超出宽度后在末尾显示省略号,这几个属性缺一不可:

  • android:ellipsize="end":明确指定文本超出范围时,在末尾显示省略号
  • android:maxLines="1":限制文本只能显示一行(这是单行省略生效的前提,别用已过时的singleLine="true"
  • android:maxWidth="160dp":设置TextView的最大宽度,超过这个值就触发截断逻辑

另外你设置的android:layout_width="wrap_content"是合理的,它会让TextView宽度自适应内容,但不会突破maxWidth的限制。

完整可用的布局代码

我帮你补全并优化了代码:

<TextView
    android:id="@+id/tvStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="10dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:maxWidth="160dp"
    android:text="Style asd sad adas cvfvd dff dzxczx zc xcc x c"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

避坑提醒

  • 千万别加android:scrollHorizontally="true",这个属性会让TextView允许横向滚动,直接跳过截断省略的逻辑
  • 如果用约束布局,还可以换一种更灵活的写法:把layout_width设为0dp,用约束属性控制最大宽度,代码如下:
<TextView
    android:id="@+id/tvStyle"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="10dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Style asd sad adas cvfvd dff dzxczx zc xcc x c"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_max="160dp" />

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

火山引擎 最新活动