Android 开发问题:TextView 内容超过宽度时,默认不会换行

  • 在 Android 开发,TextView 内容超过宽度时,默认不会换行,如下例
xml 复制代码
<TextView
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="这是一段很长的文本,这是一段很长的文本,这是一段很长的文本" />
处理策略
  1. 使用 singleLine 属性,虽然已废弃,但有效
xml 复制代码
<TextView
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:text="这是一段很长的文本,这是一段很长的文本,这是一段很长的文本" />
复制代码
# singleLine 属性已废弃

@deprecated This attribute is deprecated.
Use maxLines instead to change the layout of a static text,
and use the textMultiLine flag in the inputType attribute instead for editable text views
(if both singleLine and inputType are supplied,
the inputType flags will override the value of singleLine).
  1. 使用 maxLines 属性
xml 复制代码
<TextView
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:text="这是一段很长的文本,这是一段很长的文本,这是一段很长的文本" />
  1. 使用 maxLines 属性结合 ellipsize 属性添加省略号
xml 复制代码
<TextView
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="这是一段很长的文本,这是一段很长的文本,这是一段很长的文本" />
  • ellipsize 属性的属性值如下
属性值 说明
end 在结尾显示省略号
start 在开头显示省略号
middle 在中间显示省略号
  1. 使用跑马灯效果
xml 复制代码
<TextView
    android:id="@+id/tv_test"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:singleLine="true"
    android:text="这是一段很长的文本,这是一段很长的文本,这是一段很长的文本" />
java 复制代码
TextView tvTest = findViewById(R.id.tv_test);

tvTest.setSelected(true);
相关推荐
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
千里马学框架4 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台4 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone4 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
致远ccc4 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
ttyyttemo4 天前
Kotlin 协程中的 Job 结构化并发与取消
android
孙启超4 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust