如果有人对 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);
}
}
为了使用,下面的代码段取自一个活动,基本上在每个标签字符串周围放置一个漂亮的圆角背景,每个标签之间有一个空间缓冲区。请注意,注释掉的行只是放入背景颜色,不会产生很好的外观......
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);