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