问题描述
我想有Spannable,看起来像在IDE中的错误 - 强调与另一种颜色
I'd like to have Spannable that looks like error in IDEs - underline with another color.
我试图创建 ColorUnderlineSpan
类扩展了Android的 UnderlineSpan
,但它使所有的文字另一种颜色(我需要添加颜色的下划线只):
I've tried to create ColorUnderlineSpan
class that extends android UnderlineSpan
, but it makes all the text another color (i need to add colored underline only):
/**
* Underline Span with color
*/
public class ColorUnderlineSpan extends android.text.style.UnderlineSpan {
private int underlineColor;
public ColorUnderlineSpan(int underlineColor) {
super();
this.underlineColor = underlineColor;
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(underlineColor);
}
}
我还发现 DynamicDrawableSpan
类,但我不能看到画布边界提请。
I've also found DynamicDrawableSpan
class but i can't see canvas bounds to draw to.
这将是巨大的,得到任何Spannable实现了一套抽象的画法范围的说法。
It would be great to get any Spannable impl with abstract draw method with bounds argument.
推荐答案
这是不是prettiest解决方案,但它结束了为我工作:
This isn't the prettiest solution, but it ended up working for me:
public class CustomUnderlineSpan implements LineBackgroundSpan {
int color;
Paint p;
int start, end;
public CustomUnderlineSpan(int underlineColor, int underlineStart, int underlineEnd) {
super();
color = underlineColor;
this.start = underlineStart;
this.end = underlineEnd;
p = new Paint();
p.setColor(color);
p.setStrokeWidth(3F);
p.setStyle(Paint.Style.FILL_AND_STROKE);
}
@Override
public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
if (this.end < start) return;
if (this.start > end) return;
int offsetX = 0;
if (this.start > start) {
offsetX = (int)p.measureText(text.subSequence(start, this.start).toString());
}
int length = (int)p.measureText(text.subSequence(Math.max(start, this.start), Math.min(end, this.end)).toString());
c.drawLine(offsetX, baseline + 3F, length + offsetX, baseline + 3F, this.p);
}
这很奇怪,因为你必须指定字符索引,开始和结束用下划线,但它为我工作。
It's weird because you have to specify the character index to start and end your underlining with, but it worked for me.
这篇关于如何获得UnderlineSpan与Android的另一种颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!