android:maxEms=“5“ 为什么可以显示6个文字呢?

今天遇到一个问题,

复制代码
<TextView
    android:id="@+id/tv_bed_doctor"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:maxEms="5"
    android:ellipsize="end"
    android:textSize="@dimen/px20"
    android:includeFontPadding="false"
    android:text=""
    />

其中,父宽度为120dp+, 根据代码的意思,就是显最多显示5个字,如果还有的话,后面会显示...

但是实际情况上,如果是6个字,却可以显示完全,这是为什么呢?

android:maxEms="5" 是用来指定 TextView 最多可以显示的字符数(而不是字数)。但是,maxEms 属性是基于字体的宽度,而不是基于字符数。

在某些情况下,如果使用的是等宽字体(比如 Monospace 字体),每个字符的宽度是相同的。但是在大多数情况下,字体的宽度是不等的,一些字符可能比其他字符更宽。

因此,如果你设置了 maxEms="5",并且你的文本包含了6个字符,但这6个字符的总宽度仍然可以适应 TextView 的宽度,那么这6个字符将全部显示出来。只有当字符的总宽度超过了 TextView 的宽度时,才会根据设置的 maxEms 属性进行截断。

这种行为是符合预期的,因为 maxEms 控制的是字符的宽度,而不是字符的数量。

好吧,理解错了...

同时,我们知道maxLength 代表的是最大的长度,然后只显示当前的长度...

所以,如何解决这个问题呢,这里的宽度我们采用的是android:layout_width="wrap_content",这里,可以根据字体的宽高设置一个差不多的就可以了,比如

复制代码
<TextView
    android:id="@+id/tv_bed_doctor"
    android:layout_width="@dimen/px115"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:maxEms="5"
    android:ellipsize="end"
    android:textSize="@dimen/px20sp"
    android:includeFontPadding="false"
    android:text=""
    />

可以解决以上问题...

相关推荐
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
idjl8 小时前
Mysql测试题
android·adb
游戏开发爱好者810 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
人生游戏牛马NPC1号10 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
星辰也为你祝福h12 小时前
Android原生Dialog
android
梁同学与Android13 小时前
Android ---【CPU优化】需要优化的原因及优化的地方
android
Misha韩13 小时前
React Native 基础tabBar和自定义tabBar - bottom-tabs
android·react native
iHero14 小时前
【Nextcloud】在 Ubuntu 22.04.3 LTS 上的 Nextcloud Hub 10 (31.0.2) 后台任务cron 的优化
android·linux·ubuntu·nextcloud
yuanlaile17 小时前
Flutter Android打包学习指南
android·flutter·flutter打包·flutter android