疑惑

今天在开发过程中遇到一个神奇的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;}

更多相关文章

  1. Android基础入门教程——8.4.4 Android动画合集之属性动画-又见
  2. Android属性动画使用浅析
  3. Android 中如何将带有html格式的文章转换成能在Android中显示的
  4. android:layout_marginLeft指该控件距离边父控件的边距, android:
  5. CheckBox 设置style 没有效果的原因
  6. Android之布局onClick属性写法规则
  7. Android 采用DOM解析XML内容 【学习记录】
  8. Android studio 3.0和unity交互 Manifest文件修改后正确的内容

随机推荐

  1. android 判断是否支持闪光灯
  2. Android中C/C++的日志打印
  3. OMS:拥有Android血统的智能操作系统王
  4. Android中的异步消息处理机制Hander
  5. Android上的Back键事件捕获
  6. 如何判断用户用的是Android手机还是IOS手
  7. 2017 年 Android 领域大事件回顾
  8. Android自定义视图四:定制onMeasure强制显
  9. Android风格设计(style)
  10. Android中读取中文字符的文件与文件读取