Android SpannableString在部分文字后面设置背景

我想创建类似此图片所示的内容: 在此处输入图片说明

我设法用SpannableStringBuilder创建了Evertyhing,除了橙色的圆角矩形。我可以使用BackgroundColorSpan将背景设置为该颜色,但是我找不到使它变圆的方法。有什么想法可以实现吗?

提前致谢!

编辑:我正在使用Xamarin.Android,但这是我的代码:

stringBuilder.SetSpan(new BackgroundColorSpan(Application.Context.Resources.GetColor(Resource.Color.orangeColor)), stringBuilder.Length() - length, stringBuilder.Length(), SpanTypes.ExclusiveExclusive);

回答:

如果有人在处理罗斯福的代码示例时遇到困难(我肯定是,也许是因为它是Xamarin.Android?),这是一个更基本的Android Java版本的翻译:

    public class RoundedBackgroundSpan extends ReplacementSpan {

private static int CORNER_RADIUS = 8;

private int backgroundColor = 0;

private int textColor = 0;

public RoundedBackgroundSpan(Context context) {

super();

backgroundColor = context.getResources().getColor(R.color.gray);

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

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

}

}

为了便于使用,以下代码段取自Activity,基本上在每个标签字符串周围放置了一个圆角背景,每个标签之间都有一个空格缓冲区。请注意,注释掉的行仅带有背景色,看起来效果不佳。

SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

String between = "";

for (String tag : eventListing.getTags()) {

stringBuilder.append(between);

if (between.length() == 0) between = " ";

String thisTag = " "+tag+" ";

stringBuilder.append(thisTag);

stringBuilder.setSpan(new RoundedBackgroundSpan(this), stringBuilder.length() - thisTag.length(), stringBuilder.length() - thisTag.length() + thisTag.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

//stringBuilder.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.gray)), stringBuilder.length() - thisTag.length(), stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

TextView tv = new TextView(this);

tv.setText(stringBuilder);

以上是 Android SpannableString在部分文字后面设置背景 的全部内容, 来源链接: utcz.com/qa/430412.html

回到顶部