本文将带你了解Android应用开发Android TextView关于android:ellipsize=end的一个神奇bug解决方案,希望本文对大家学Android有所帮助。
疑惑
今天在开发过程中遇到一个神奇的bug:
需求很明确,TextView配置了关键的以下两行属性:
很简单的需求,个人觉得也没什么问题,结果竟然如下:
有点奇怪,在…后面竟然还会显示内容,更令人窝火的是,这些尾随的文字竟然还只显示到一半!
解决
网上搜索一下,有很多相关的解决方案:
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{
@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;
}
"
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!