gpt4 book ai didi

用于 Spannable 的 Android 填充?

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:57 24 4
gpt4 key购买 nike

我使用这段代码为 TextView 中的一段文本设置背景:

s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.selection_blue)), prevIndex, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但是我也需要为这个文本设置填充。可能吗?

最佳答案

您可以使用 ReplacementSpan。在您的 Activity 中:

TextView tagsTextView = (TextView) mView.findViewById(R.id.tagsTextView);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

SpannableString tag = new SpannableString("TEST");
stringBuilder.append(tag);
stringBuilder.setSpan(new TagSpan(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)), stringBuilder.length() - tag.length(), stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tagsTextView.setText(stringBuilder, TextView.BufferType.SPANNABLE);

TagSpan.java

public class TagSpan extends ReplacementSpan {
private static final float PADDING = 50.0f;
private RectF mRect;
private int mBackgroundColor;
private int mForegroundColor;

public TagSpan(int backgroundColor, int foregroundColor) {
this.mRect = new RectF();
this.mBackgroundColor = backgroundColor;
this.mForegroundColor = foregroundColor;
}

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
// Background
mRect.set(x, top, x + paint.measureText(text, start, end) + PADDING, bottom);
paint.setColor(mBackgroundColor);
canvas.drawRect(mRect, paint);

// Text
paint.setColor(mForegroundColor);
int xPos = Math.round(x + (PADDING / 2));
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
canvas.drawText(text, start, end, xPos, yPos, paint);
}

@Override
public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
return Math.round(paint.measureText(text, start, end) + PADDING);
}
}

关于用于 Spannable 的 Android 填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727343/

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