您的位置:首页 > 移动开发 > Android开发

Android TextView关于android:ellipsize=end的一个bug

2017-11-03 18:39 1561 查看

疑惑

今天在开发过程中遇到一个神奇的bug:

需求很明确,TextView配置了关键的以下两行属性:

<!--内容最大为2行,若内容过多,以...结尾-->
<!--android:ellipsize="end"-->
<!--android:maxLines="2"-->
<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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐