Android: Adding Padding to BackgroundColorSpan

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:

BackgroundColorSpan Example

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:

Image for post
Image for post

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:

Image for post
Image for post

Much better!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store