On Android you can often run into a problem of adding a background color to each line of a TextView instead of the entire text to create a wrap-around effect of some sort. The simple way of doings this to use a BackgroundColorSpan or LineBackgroundSpan like so:
The main problem with this approach it that the background is drawn only behind the text, and you can’t specify any sort of padding for each line:
Let’s just say it looks pretty ugly, especially on the left and the right of the each line.
A typical suggestion to fix this issue is to use a ReplacementSpan, which works well, but only in case you have a single line in the TextView. If you have multiple lines like in the example above, you are out of luck.
I have found that the easiest way to accomplish the desired affect is to use a custom LineBackgoundSpan with a bit of a hack.
Here is our custom PaddingBackgroundColorSpan:
The trick here is to use the specified padding and draw outside of the bounds of the original Rect provided to the drawBackground method. This almost works, but we quickly run into the problem that the background gets clipped by the bounds of the TextView.
To work around that we can add a padding and an invisible shadow layer to the TextView, which will effectively expand the clip bounds:
Here is final result: