问题的描述
由于项目的需求,需要实现TextView的富文本效果,TextView头部需要添加一张小图片,然后能支持部分文字变色可点击,
查询了部分资料是用SpannableString实现的。
<TextView
android:maxLines="2"
android:ellipsize="end"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
(我这里是限制2行,超出则以…结尾)但是后来发现应用富文本风格后,这个以…结束的效果失效了
问题分析
上网查询后不少人都遇到这个问题,主要的解决办法是截断字符段,把超出的部分用“…”替换,以达到我们的效果
解决办法
先说布局文件,TextView我是放在列表中,我这里是写了2个相同的TextView,底部一个设置不可见,设置为invisible,
不能设置为了gone。
(这里说下为啥要2个的原因:因为只有一个的时候,我的列表下拉刷新的时候,TEXTVIEW会有跳动的情况,为了优化这个体验我采用两个,如果有更好的办法请指出,谢谢)
布局文件
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvTempContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/app_black_color"
android:maxLines="2"
android:visibility="invisible"
android:textSize="13sp"/>
<TextView
android:id="@+id/tvContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/app_black_color"
android:maxLines="2"
android:textSize="13sp"/>
</RelativeLayout>
底部一个TextView用于计算出第二行最后一个字符的位置,然后进行截断处理
Java代码部分 tempTextView用于计算,textView来显示结果
tempTextView.setText(feed.getContent());
tempTextView.post(new Runnable() {
@Override
public void run() {
String text;
if (tvTempContent.getLineCount() >= 2) {//如果只有一行,就不需要做处理了
int lineEndIndex = tvTempContent.getLayout().getLineEnd(1);//第二行最后一个字符的位置
int lengthAll = tvTempContent.getText().length();
if (lineEndIndex >= lengthAll) {//说明没有超出2行
text = feed.getContent();
} else {//否则超出两行了
String endTag = "...";
//计算省略号的宽度
int endTagWidth = testStrWidth(tvTempContent, endTag);
int replaceIndex = 1;
//数字、符号、中文占用的宽度都不同,所以这里计算下需要替换的字符的个数,最多三个
//这里有人直接替换3个,有人替换1个字符,经过测试发现不同类型的字符,宽度是不一样的
//我当时写的demo上,如果是中文,省略号只需要占用1个字符,如果数字要2个,如果是逗号,要3个
//为了兼容这些情况,我做了如下的处理,去计算宽度后,再决定截取,最多截取三个
while (replaceIndex < 3) {
String endText = tvTempContent.getText().subSequence(lineEndIndex - replaceIndex, lineEndIndex).toString();
if (testStrWidth(tvTempContent, endText) < endTagWidth) {
replaceIndex ++;
} else {
break;
}
}
text = tvTempContent.getText().subSequence(0, lineEndIndex - replaceIndex) + "...";
}
} else {
text = feed.getContent();
}
//这里的text则是已经截取过的字符是带...结束的字符串,可以在这里做富文本处理
textView.setText(text);
}
});
最后出来的效果图