How to get UnderlineSpan with a different color in Android?

I would like Spanable to look like an error in the IDE - underlining with a different color.

I tried to create a ColorUnderlineSpan class that extends the Android UnderlineSpan , but it makes all the text in a different color (I need to add only a color underline):

 /** * 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); } } 

I also found the DynamicDrawableSpan class, but I do not see the borders of the canvas to draw.

It would be great to get any Spannable impl with an abstract draw method with bounds argument.

+2
source share
1 answer

This is not the most suitable solution, but in the end I worked 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); } 

This is strange because you need to specify a character index to start and end your underscore, but it worked for me.

+5
source

Source: https://habr.com/ru/post/984519/


All Articles