gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:46:00 66 4
gpt4 key购买 nike

我想创建与此图片类似的东西: enter image description here

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

提前致谢!

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

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

最佳答案

如果有人对 Roosevelt 的代码示例有疑问(我确定是,可能是因为它是 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 在部分文本后面设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292838/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com