Android Spannablecontent With Rounded Corners

前端 未结 8 881
无人及你
无人及你 2020-12-13 15:06

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

8条回答
  •  不思量自难忘°
    2020-12-13 15:43

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

提交回复
热议问题