4

検索された用語を強調表示するためにTextView、内部にがあります。SpannableStringそのようです :

ここに画像の説明を入力

<TextView android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:id="@+id/textBox"
          android:textSize="16sp"
          android:paddingTop="10dp"
          android:paddingLeft="20dp"
          android:paddingRight="20dp"
          android:lineSpacingExtra="5dp"
          android:textColor="@color/TextGray"/>

android:lineSpacingExtraご覧のとおり、線に適切な間隔を与えるために使用していますが、SpannableString背景が高すぎます。行間の間隔を維持したいが、SpannableString短くしたい。

これはどのように可能ですか?

4

1 に答える 1

4

ReplacementSpanを拡張することで、独自のスパンを作成できます。メソッドでは、パラメータから取得できるものをdraw考慮することができます。fontSpacingPaint

このような:

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

public class BetterHighlightSpan extends ReplacementSpan {

    private int backgroundColor;
    public BetterHighlightSpan(int backgroundColor) {
        super();
        this.backgroundColor = backgroundColor;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
        return Math.round(paint.measureText(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) {

        // save current color
        int oldColor = paint.getColor();

        // calculate new bottom position considering the fontSpacing
        float fontSpacing = paint.getFontSpacing();
        float newBottom = bottom - fontSpacing;

        // change color and draw background highlight
        RectF rect = new RectF(x, top, x + paint.measureText(text, start, end), newBottom);
        paint.setColor(backgroundColor);
        canvas.drawRect(rect, paint);

        // revert color and draw text
        paint.setColor(oldColor);
        canvas.drawText(text, start, end, x, y, paint);
    }

}

次のように使用できます。

TextView textView = (TextView) findViewById(R.id.textView);
SpannableStringBuilder builder = new SpannableStringBuilder("here some text and more of it");
builder.setSpan(new BetterHighlightSpan(Color.CYAN), 4, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(builder);

あまりテストできませんでしたが、改善できます。

于 2013-12-07T01:07:07.687 に答える