如何限制spannablestring的行高,但保持其余的行

时间:2013-12-07 00:07:27

标签: android formatting textview highlight spannablestring

我有一个TextView,里面有SpannableString来突出搜索的字词。像这样:

enter image description here

<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更短。

这怎么可能?

1 个答案:

答案 0 :(得分:4)

您可以通过扩展ReplacementSpan来创建自己的范围。在draw方法中,您可以考虑从fontSpacing参数中获得的Paint

像这样:

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);

我无法测试它,但你可以改进它。