I have an app where I am displaying multiple lines, and multiple paragraphs, of formatted text in a TextView. I am using SpannableStringBuilder for this purpose.
One of the things I want to do here is to be able to highlight the text. Now I have tried using BackgroundColorSpan, but in this case, the background on the text covers the complete line-height. I want it to cover only the text instead. There seems to be no apparent way to set a vertical padding or height on this span. Just the colour.
Secondly, I also tried subclassing ReplacementSpan and implementing a backgroundSpan of my own by drawing in the draw method of this class. But this doesn't seem to support multiline highlighting.
Can anyone tell me how I can go about achieving this highlighting functionality? Basically, I want it to work like an ebook reader, preferably the Kindle or the default Book reader on Android.
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)
You can modify the "top" and "bottom" arguments to specify the height of the background you are drawing for a given line. The "baseline" argument is the the y-coordinate of the line that all the characters sit on (notice that the letters g, p, j etc. have some parts that fall below the baseline).
This method is applied for every line on the display for a given text. For example if the text
spans 3 lines on your display, then drawBackground(...) is applied thrice, and you can use the "lnum" argument to change the behavior for certain lines if you are looking to only change the height of certain lines in the span.