Android paddings for spannable?

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

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

But I also need to install an add-on for this text. Is it possible?

+4
source share
1 answer

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); } } 
+2
source

All Articles