7

I'm trying to apply a background with a border to specific text in a TextView. A BackgroundColorSpan works great, but it doesn't have a border. To get the border, I instead use a custom ReplacementSpan and override draw. It looks good for short words/sentences, but it fails to wrap lines. How can I make my custom ReplacementSpan wrap?

enter image description here

enter image description here

enter image description here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_replacement_span);

    final Context context = this;
    final TextView tv = (TextView) findViewById(R.id.tv);


    Spannable span = Spannable.Factory.getInstance().newSpannable("Some long string that wraps");
    //Works great, but no border:
    //span.setSpan(new BackgroundColorSpan(Color.GREEN), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

    //Has border, but doesn't wrap:
    span.setSpan(new BorderedSpan(context), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

    tv.setText(span, TextView.BufferType.SPANNABLE);
}


public static class BorderedSpan extends ReplacementSpan {
    final Paint mPaintBorder, mPaintBackground;
    int mWidth;
    Resources r;
    int mTextColor;

    public BorderedSpan(Context context) {
        mPaintBorder = new Paint();
        mPaintBorder.setStyle(Paint.Style.STROKE);
        mPaintBorder.setAntiAlias(true);

        mPaintBackground = new Paint();
        mPaintBackground.setStyle(Paint.Style.FILL);
        mPaintBackground.setAntiAlias(true);

        r = context.getResources();

        mPaintBorder.setColor(Color.RED);
        mPaintBackground.setColor(Color.GREEN);
        mTextColor = Color.BLACK;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //return text with relative to the Paint
        mWidth = (int) paint.measureText(text, start, end);
        return mWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        canvas.drawRect(x, top, x + mWidth, bottom, mPaintBackground);
        canvas.drawRect(x, top, x + mWidth, bottom, mPaintBorder);
        paint.setColor(mTextColor); //use the default text paint to preserve font size/style
        canvas.drawText(text, start, end, x, y, paint);
    }
}
adamdport
  • 11,687
  • 14
  • 69
  • 91

0 Answers0