我需要在TextView中使用自定义下划线。 我使用ReplacementSpan来做到这一点。但它会在第一行末尾删除文本。
这是我的CustomUnderlineSpan
课程:
public class CustomUnderlineSpan extends ReplacementSpan {
private int underlineColor;
private int textColor;
public CustomUnderlineSpan(int underlineColor, int textColor) {
super();
this.underlineColor = underlineColor;
this.textColor = textColor;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
paint.setStrokeWidth(3F);
paint.setColor(textColor);
canvas.drawText(text, start, end, x, y, paint);
paint.setColor(underlineColor);
int length = (int) paint.measureText(text.subSequence(start, end).toString());
canvas.drawLine(x, bottom, length + x, bottom, paint);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return Math.round(paint.measureText(text, start, end));
}
}
这是为所有文字长度实施CustomUnderlineSpan
的方法:
public static Spannable getCustomUnderlineSpan(String string, int underlineColor, int textColor) {
Spannable spannable = new SpannableString(string);
CustomUnderlineSpan customUnderlineSpan = new CustomUnderlineSpan(underlineColor, textColor);
spannable.setSpan(customUnderlineSpan, 0, spannable.length(), 0);
return spannable;
}
这里是将文本设置为TextView:
String text = "Just text to underline Just text to underline Just text" +
"to underline Just text to underline Just text to underline Just text" +
"to underline Just text to underline Just text to underline";
textView.setText(getCustomUnderlineSpan(text,
Color.parseColor("#0080ff"), Color.parseColor("#000000")), TextView.BufferType.SPANNABLE);
你有什么建议为什么文字在行尾切断? 谢谢!
答案 0 :(得分:2)
<强>解决强>
使用DynamicDrawableSpan
代替ReplacementSpan
解决了这个问题。
似乎ReplacementSpan
不能执行换行符。
这是我的代码:
public class CustomUnderlineSpan extends DynamicDrawableSpan {
private int underlineColor;
private int textColor;
private final float STROKE_WIDTH = 3F;
public CustomUnderlineSpan(int underlineColor, int textColor) {
super(DynamicDrawableSpan.ALIGN_BASELINE);
this.underlineColor = underlineColor;
this.textColor = textColor;
}
@Override
public Drawable getDrawable() {
return null;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
Paint.FontMetricsInt fm) {
return (int) paint.measureText(text, start, end);
}
@Override
public void draw(Canvas canvas, CharSequence text,
int start, int end, float x,
int top, int y, int bottom, Paint paint) {
int length = (int) paint.measureText(text.subSequence(start, end).toString());
paint.setColor(underlineColor);
paint.setStrokeWidth(STROKE_WIDTH);
canvas.drawLine(x, bottom - STROKE_WIDTH / 2, length + x, bottom - STROKE_WIDTH / 2, paint);
paint.setColor(textColor);
canvas.drawText(text.subSequence(start, end).toString(), x, y, paint);
}
}