使用 spannable 分隔字符串中的单词

using spannable to seperate words in a String

我不想在我的空间上使用 SPAN

我有一个字符串,例如:

字符串项 = "鲜花巧克力蜡烛";

我需要做的是像这样打印这个字符串:

我可以在 Java 中使用 spannable 来做到这一点吗?如果是,如何?

我有这个 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);
    }
}

对此有两种解决方案。您可以为每个单词添加一个 RoundedBackgrondSpan,也可以修改您的 RoudedBackgroundSpan,因为它当前绘制的是一个矩形。

第一种方法可能更容易。

使用这个功能:

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