Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagarpatel288/fcb0c1925dd6feb3a76582ccb47f917b to your computer and use it in GitHub Desktop.
Save sagarpatel288/fcb0c1925dd6feb3a76582ccb47f917b to your computer and use it in GitHub Desktop.
Android TextView, that allows changing the letter spacing of the text. @author: Pedro Barros
/**
* Text view that allows changing the letter spacing of the text.
*
* @author Pedro Barros (pedrobarros.dev at gmail.com)
* @since May 7, 2013
*/
public static class LetterSpacingTextView extends TextView {
private float spacing = Spacing.NORMAL;
private CharSequence originalText = "";
public LetterSpacingTextView(Context context) {
super(context);
}
public LetterSpacingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public float getSpacing() {
return this.spacing;
}
public void setSpacing(float spacing) {
this.spacing = spacing;
applySpacing();
}
@Override
public void setText(CharSequence text, BufferType type) {
originalText = text;
applySpacing();
}
@Override
public CharSequence getText() {
return originalText;
}
private void applySpacing() {
if (this == null || this.originalText == null) return;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < originalText.length(); i++) {
builder.append(originalText.charAt(i));
if (i + 1 < originalText.length()) {
builder.append("\u00A0");
}
}
SpannableString finalText = new SpannableString(builder.toString());
if (builder.toString().length() > 1) {
for (int i = 1; i < builder.toString().length(); i += 2) {
finalText.setSpan(new ScaleXSpan((spacing + 1) / 10), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
super.setText(finalText, BufferType.SPANNABLE);
}
public class Spacing {
public final static float NORMAL = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment