我像这样在字符串中设置了背景:
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()。
发布于 2018-05-12 02:36:47
我想这对你有帮助。设置textView宽度与父对象匹配。main_activity.xml
<TextView
   android:width="match_parent"https://stackoverflow.com/questions/20069537
复制相似问题