Android(安卓)TextView关于android:ellipsize=end的一个bug
16lz
2021-12-04
疑惑
今天在开发过程中遇到一个神奇的bug:
需求很明确,TextView配置了关键的以下两行属性:
<TextView android:id="@+id/tv_content" android:layout_width="0dp" android:layout_height="0dp" android:ellipsize="end" android:maxLines="2" app:layout_constraintBottom_toTopOf="@+id/divider" app:layout_constraintLeft_toRightOf="@+id/tv_icon" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_title"/>
很简单的需求,个人觉得也没什么问题,结果竟然如下:
有点奇怪,在…后面竟然还会显示内容,更令人窝火的是,这些尾随的文字竟然还只显示到一半!
解决
网上搜索一下,有很多相关的解决方案:
1.添加/删除/配置 这些属性:
android:singleLine = "false" android:lines = "2" android:ellipsize="end" android:maxLines="2"
结果并没有解决问题
2.强制规范TextView内容的长度,比如String.split()或者其他
不靠谱的方案,完全是不知道原因的情况下去解决。
3.解决
最后找到了这个网址,找到了原因所致:
Strange issue with android:ellipsize=end
It turns out it was the new line character ‘\n’ that was causing it. Even if the new line was after the ellipsize, the new line character was [inconsistently] causing this problem as long as it was somewhere within the string.
就是说,textView的文本内容中包含\n字符或者其它html字符比如\<.*?>
这些特殊字符就是导致异常的原因。
解决方案也很简单,直接在setText之前调用:
myText.replaceAll("\\<.*?>","");
补充
这些文字的内容是从服务器所得,因此,为了不修改业务代码,直接在Gson解析的时候将内容进行修改。
直接自定义TypeAdapter解析该属性,同时还能提高解析时的性能。
/** * Created by QingMei on 2017/11/3. * desc:remove all html char or \n in string */public class MessageContentAdapter extends TypeAdapter<String> { @Override public void write(JsonWriter out, String value) throws IOException { } @Override public String read(JsonReader in) throws IOException { return in.nextString().replaceAll("\\<.*?>|\\n",""); }}
在实体类对象中添加注解:
public class Message implements Serializable { private int id; ... ... ... @JsonAdapter(MessageContentAdapter.class) private String description;}
更多相关文章
- mybatisplus的坑 insert标签insert into select无参数问题的解决
- Android基础入门教程——8.4.4 Android动画合集之属性动画-又见
- Android界面编程——Android基本控件
- Android逆向之旅---Android中的sharedUserId属性详解
- Android属性动画使用浅析
- Android(安卓)代码设置RelativeLayout元素居中
- 应用系统样式延伸
- android开机自启广播无效果的曲线解决方案
- 编码工具类EncodingUtils(解决乱码问题)