BackgroundColorSpan will adjust the height or add indents to it

I have an application in which I show several lines and several paragraphs of formatted text in TextView. For this I use SpannableStringBuilder.

One of the things I want to do here is to highlight the text. Now I tried to use BackgroundColorSpan, but in this case, the background in the text covers the full height of the line. I want it to cover only text. There seems to be no obvious way to set the vertical fill or height at this gap. Only color.

Secondly, I also tried to subclass ReplacementSpanand implement my own backgroundSpanusing the drawing method of this class. But this does not seem to support multi-line backlighting.

Can someone tell me how can I achieve this highlight function? Basically, I want it to work as an e Kindle-book reader , preferably or a default book reader on Android.

+4
source share
2 answers

You can implement LineBackgroundSpan and override:

drawBackground (Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum)

"" "" , , . "" - y , ( , g, p, j .. , ).

. ,

"this is an example , blah, blah .." 

3 , drawBackground (...) , "lnum" , .

+1

koopuluri, LineBackgroundSpan , . ResplacementSpan, draw . .

/**
 * It like a {@link android.text.style.BackgroundColorSpan} but we don't paint the extra line height.
 * <p/>
 */
public class BackgroundColorWithoutLineHeightSpan extends ReplacementSpan
{
    private final int mColor;
    private final int mTextHeight;

    public BackgroundColorWithoutLineHeightSpan(int color, int textHeight)
    {
        mColor = color;
        mTextHeight = textHeight;
    }

    @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)
    {
        int paintColor = paint.getColor();
        RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), top + mTextHeight);
        paint.setColor(mColor);
        canvas.drawRect(rect, paint);
        paint.setColor(paintColor);
        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);
    }
}
0

All Articles