-1

I DON'T WANT SPAN ON MY SPACES

I have a string, for example:

String items = " flowers chocolates candles ";

What I need to do is print this string like this:

enter image description here

Can I do this using spannable in Java? If yes, how ?

I have this RoundedBackgroundSpan class:

public class RoundedBackgroundSpan extends ReplacementSpan {

    private static final int CORNER_RADIUS = 8;
    private int backgroundColor = 0;
    private int textColor = 0;

    public RoundedBackgroundSpan(Context context) {
        super();
        backgroundColor = context.getResources().getColor(R.color.colorPrimary);
        textColor = context.getResources().getColor(R.color.white);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom - 2);
        paint.setColor(backgroundColor);
        canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, paint);
        paint.setColor(textColor);
        canvas.drawText(text, start, end, x, y, paint);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end));
    }

    private float measureText(Paint paint, CharSequence text, int start, int end) {
        return paint.measureText(text, start, end);
    }
}
Srijan
  • 43
  • 7
  • 1
    Does this answer your question? [Background color to spanableString in android](https://stackoverflow.com/questions/25724117/background-color-to-spanablestring-in-android) – ADM Mar 24 '21 at 05:06
  • No, I want the spannable to break with every space in the string and start again. – Srijan Mar 24 '21 at 10:33

2 Answers2

1

There's two solutions for this. You can either add a RoundedBackgrondSpan to each word, or you can modify your RoudedBackgroundSpan as currently it draws a single rectangle.

The first approach would probably be easier.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
1

use this function:

private Spannable spanWords(String message) {
    int start = 0;
    String[] words = message.split(" ");
    Spannable spannable = new SpannableString(message);
    for (String word : words) {
        spannable.setSpan(new RoundedBackgroundSpan(getContext()), start, (start + word.length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        start += word.length() + 1;
    }
    return spannable;
}
Nilesh B
  • 937
  • 1
  • 9
  • 14