在界面上需要展示一个textview,默认超过4行则在末尾添加"展开",用户点击展开文本后则完整显示文本,同时末尾添加“收起”。
先列出textview的布局
<textview
android:id="@ id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginstart="20dp"
android:layout_marginend="20dp"
android:textcolor="#666666"
android:linespacingextra="3dp"
android:textsize="13sp"
/>
由于我们需要根据文本是否达到4行来做对应展示,很自然的想到要在textview布局完成之后再处理,此处设置onpredrawlistener
contenttextview.getviewtreeobserver()
.addonpredrawlistener(new viewtreeobserver.onpredrawlistener() {
@override
public boolean onpredraw() {
contenttextview.getviewtreeobserver().removeonpredrawlistener(this);
expandtext();
return false;
}
});
在expandtext中,如果文本布局超过4行,我们需要截取第四行,在文本后面预留展开的位置,最后通过设置span添加点击事件,收起功能类似。
string expand = "[展开]";
string collapse = "[收起]";
private void expandtext() {
charsequence text = contenttextview.gettext();
int width = contenttextview.getwidth();
textpaint paint = contenttextview.getpaint();
layout layout = contenttextview.getlayout();
int line = layout.getlinecount();
if (line > 4) {
int start = layout.getlinestart(3);
int end = layout.getlinevisibleend(3);
charsequence lastline = text.subsequence(start, end);
float expandwidth = paint.measuretext(expand);
float remain = width - expandwidth;
charsequence ellipsize =
textutils.ellipsize(lastline,
paint,
remain,
textutils.truncateat.end);
clickablespan clickablespan = new clickablespan() {
@override
public void onclick(@nonnull view widget) {
collapsetext();
}
};
spannablestringbuilder ssb = new spannablestringbuilder();
ssb.append(text.subsequence(0, start));
ssb.append(ellipsize);
ssb.append(expand);
ssb.setspan(new foregroundcolorspan(0xff7369f8),
ssb.length() - expand.length(), ssb.length(),
spanned.span_inclusive_exclusive);
ssb.setspan(clickablespan,
ssb.length() - expand.length(), ssb.length(),
spanned.span_inclusive_exclusive);
contenttextview.setmovementmethod(linkmovementmethod.getinstance());
contenttextview.settext(ssb);
}
}
private void collapsetext() {
// 默认此时文本肯定超过行数了,直接在最后拼接文本
clickablespan clickablespan = new clickablespan() {
@override
public void onclick(@nonnull view widget) {
expandtext();
}
};
spannablestringbuilder ssb = new spannablestringbuilder();
ssb.append(bean.getmsg());
ssb.append(collapse);
ssb.setspan(new foregroundcolorspan(0xff7369f8),
ssb.length() - collapse.length(), ssb.length(),
spanned.span_inclusive_exclusive);
ssb.setspan(clickablespan,
ssb.length() - collapse.length(), ssb.length(),
spanned.span_inclusive_exclusive);
contenttextview.settext(ssb);
}