11

私はそのような文字列で背景を設定します:

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() が正しく呼び出されます。

4

7 に答える 7

24

誰かがこの問題を抱えている場合に備えて、私はそれに遭遇しました。私がしなければならなかったことは、2 番目のパラメーターを setText() メソッドに渡すことです。私の電話は次のように見えました

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

お役に立てれば!

于 2014-09-30T22:28:27.220 に答える
4

この問題に対する実用的な(しかしハッキーな)解決策を見つけたようです。スパンに含まれないように、文字列の最後に別の記号を追加してみてください - そしてdraw()呼び出されます!

 char EXTRA_SPACE = ' ';
 String text = originalString + EXTRA_SPACE;
 Spannable spannable = new SpannableString(text);
 spannable.setSpan(new MyReplacementSpan(), 0, text.length()-1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
 textView.setText(spannable);

文字列全体の幅であるスパンを無視しているようです。

于 2015-08-23T19:37:50.423 に答える
0

invalidate()強制的に呼び出すために、そのビューのメソッドを呼び出しdraw()ます。

于 2013-11-19T11:14:04.620 に答える