I am trying to change my string to make a badge with a number in the middle by using Spannable String. I can highlight the appropriate letter/number by setting the BackGrou
Here's an improved version based on @ericlokness answer, with custom background and text colors. It also works with multiple spans on the same TextView.
public class RoundedBackgroundSpan extends ReplacementSpan
{
private final int _padding = 20;
private int _backgroundColor;
private int _textColor;
public RoundedBackgroundSpan(int backgroundColor, int textColor) {
super();
_backgroundColor = backgroundColor;
_textColor = textColor;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return (int) (_padding + paint.measureText(text.subSequence(start, end).toString()) + _padding);
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)
{
float width = paint.measureText(text.subSequence(start, end).toString());
RectF rect = new RectF(x - _padding, top, x + width + _padding, bottom);
paint.setColor(_backgroundColor);
canvas.drawRoundRect(rect, 20, 20, paint);
paint.setColor(_textColor);
canvas.drawText(text, start, end, x, y, paint);
}
}