【发布时间】:2018-10-26 05:01:20
【问题描述】:
我需要为我的 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);
你有什么建议为什么会在行尾删减文本? 谢谢!
【问题讨论】:
标签: android string android-edittext textview spannablestring