gpt4 book ai didi

android - ReplacementSpan 的 draw() 方法未被调用

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:51:53 24 4
gpt4 key购买 nike

我这样在字符串中设置背景:

spanString.setSpan(new BackgroundColorSpan(color), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

但我想在此背景中增加左右填充,所以我创建了自定义跨度

public class PaddingBackgroundSpan extends ReplacementSpan {
private int mBackgroundColor;
private int mForegroundColor;

public PaddingBackgroundSpan(int backgroundColor, int foregroundColor) {
this.mBackgroundColor = backgroundColor;
this.mForegroundColor = foregroundColor;
}

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

}

@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(mBackgroundColor);
canvas.drawRect(rect, paint);
paint.setColor(mForegroundColor);
canvas.drawText(text, start, end, x, y, paint);
}

private float measureText(Paint paint, CharSequence text, int start, int end) {
return paint.measureText(text, start, end);
}

我通过以下方式使用我的跨度:

spanString.setSpan(new PaddingBackgroundSpan(color1, color2), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

不幸的是,我的 draw() 方法没有被调用。 getSize() 被正确调用。

最佳答案

如果有人遇到这个问题,我遇到过。我必须做的是将第二个参数传递给 setText() 方法。我的电话看起来像

textView.setText(spanned, TextView.BufferType.SPANNABLE);

希望这对您有所帮助!

关于android - ReplacementSpan 的 draw() 方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20069537/

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