4

I use this code to set background for piece of text inside TextView:

s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.selection_blue)), prevIndex, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

But I need to set padding for this text too. Is it possible?

alwx
  • 205
  • 1
  • 3
  • 14
  • 2
    Can't you just set the padding of the TextView displaying the spannable? – Slickelito Dec 05 '12 at 16:17
  • I think there is other text inside the TextView, which should not get the padding (for example, the part with the background color is a quote) – dermatthias Apr 11 '13 at 08:40
  • I've looked for this myself and can't find any documentation for it anywhere - certainly not for padding separate spans within a TextView (which is what I'm trying to do) – saywhatnow Mar 20 '14 at 00:33
  • You could add a space before and after the spanned text. – Suragch Feb 28 '15 at 09:46

1 Answers1

2

You can use ReplacementSpan. In your Activity:

TextView tagsTextView = (TextView) mView.findViewById(R.id.tagsTextView);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

SpannableString tag = new SpannableString("TEST");
stringBuilder.append(tag);
stringBuilder.setSpan(new TagSpan(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)), stringBuilder.length() - tag.length(), stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tagsTextView.setText(stringBuilder, TextView.BufferType.SPANNABLE);

TagSpan.java

public class TagSpan extends ReplacementSpan {
    private static final float PADDING = 50.0f;
    private RectF mRect;
    private int mBackgroundColor;
    private int mForegroundColor;

    public TagSpan(int backgroundColor, int foregroundColor) {
        this.mRect = new RectF();
        this.mBackgroundColor = backgroundColor;
        this.mForegroundColor = foregroundColor;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        // Background
        mRect.set(x, top, x + paint.measureText(text, start, end) + PADDING, bottom);
        paint.setColor(mBackgroundColor);
        canvas.drawRect(mRect, paint);

        // Text
        paint.setColor(mForegroundColor);
        int xPos = Math.round(x + (PADDING / 2));
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
        canvas.drawText(text, start, end, xPos, yPos, paint);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end) + PADDING);
    }
}
Andrea Motto
  • 1,540
  • 21
  • 38