Is there a way to adjust the spacing between characters in an Android TextView
? I believe this is typically called "kerning".
I'm aware of the android:textScaleX
attribute, but that compresses the characters along with the spacing.
Is there a way to adjust the spacing between characters in an Android TextView
? I believe this is typically called "kerning".
I'm aware of the android:textScaleX
attribute, but that compresses the characters along with the spacing.
AFAIK, you cannot adjust kerning in
TextView
. You may be able to adjust kerning if you draw the text on theCanvas
yourself using the 2D graphics APIs.One more solution.
Where pixel_1dp is XML:
To set spacing use code like this:
It's difficult to adjust spacing between characters, when you are using TextView. But if you can handle the drawing yourself, there should be some way to do that.
My answer to this question is: use your custom Span .
My code:
Explain:
Building your own
Span
can help you achieve many amazing effect, like make a blur TextView, change the background or foreground for your TextView, even make some animation. I learn a lot from this post Span a powerful concept .Because you are adding spacing to each character, so we should use a character level base span, in this case, ReplacementSpan is the best choice. I add a
spacing
method, so when using it, you can simply pass the space you want for each character as parameter.When building your custom span, you need to override at least two method,
getSize
anddraw
. ThegetSize
method should return the final width after we add the spacing for the whole charsequence, and inside thedraw
method block, you can control theCanvas
to do the drawing you want.So how we use this LetterSpacingSpan? It's easy:
Usage:
And that's it.
Since Android 21, you can use set the
letterSpacing
attribute.The only way I found to adjust the kerning, is to create a custom font in which the glyph advance is altered.
I wanted to use @PedroBarros answer, but by defining what the spacing should be in pixel.
Here's my edit to the applySpacing method :
I'm a beginner as an Android developer, please feel free to let me know if this is not good !