要实现这样的效果:
用UnderlineSpan、Html实现的效果不是很好,决定继承LineBackgroundSpan逐行画线,效果不错。记录下:
/**
* 自定义的UnderlineSpan,用于给TextView底部画直线
*
* 建议在layout里给textView设置includeFontPadding=false,并且设置lineSpacingMultiplier/lineSpacingExtra
* 和paddingBottom以留出底部空间画线
*/
public class CustomUnderlineSpan implements LineBackgroundSpan {
private Paint paint;
private TextView textView;
private float offsetY;
/**
*
* @param textView 被画线的textview
* @param color 底部画线的颜色
* @param lineHeight 画线的高度(像素值)
* @param offsetY 画线相对于textView行高从上往下的偏移距离(像素值)
*/
public CustomUnderlineSpan(TextView textView, int color, float lineHeight, float offsetY) {
paint = new Paint();
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(lineHeight);
this.textView = textView;
this.offsetY = offsetY;
}
@Override
public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
int bottom, CharSequence text, int start, int end, int lnum) {
int lineNum = textView.getLineCount();
Layout layout = textView.getLayout();
float y;
for (int i = 0; i < lineNum; i++) {
y = layout.getLineTop(i) + offsetY;
canvas.drawLine(layout.getLineLeft(i), y, layout.getLineRight(i), y, paint);
}
}
}
调起来:
SpannableString ss = new SpannableString(text);
ss.setSpan(new CustomUnderlineSpan(binding.title,
Color.parseColor("#C7FFE921"),
UIUtil.INSTANCE.dipToPixels(8),
UIUtil.INSTANCE.dipToPixels(22)),
0, intSpannableStringBuilderLength,
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
title.setText(ss);