· 8 years ago · Nov 16, 2017, 04:06 AM
1/**
2 * Text view that allows changing the letter spacing of the text.
3 *
4 * @author Pedro Barros (pedrobarros.dev at gmail.com)
5 * @since May 7, 2013
6 */
7 public static class LetterSpacingTextView extends TextView {
8 private float spacing = Spacing.NORMAL;
9 private CharSequence originalText = "";
10
11 public LetterSpacingTextView(Context context) {
12 super(context);
13 }
14
15 public LetterSpacingTextView(Context context, AttributeSet attrs) {
16 super(context, attrs);
17 }
18
19 public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
20 super(context, attrs, defStyle);
21 }
22
23 public float getSpacing() {
24 return this.spacing;
25 }
26
27 public void setSpacing(float spacing) {
28 this.spacing = spacing;
29 applySpacing();
30 }
31
32 @Override
33 public void setText(CharSequence text, BufferType type) {
34 originalText = text;
35 applySpacing();
36 }
37
38 @Override
39 public CharSequence getText() {
40 return originalText;
41 }
42
43 private void applySpacing() {
44 if (this == null || this.originalText == null) return;
45 StringBuilder builder = new StringBuilder();
46 for (int i = 0; i < originalText.length(); i++) {
47 builder.append(originalText.charAt(i));
48 if (i + 1 < originalText.length()) {
49 builder.append("\u00A0");
50 }
51 }
52 SpannableString finalText = new SpannableString(builder.toString());
53 if (builder.toString().length() > 1) {
54 for (int i = 1; i < builder.toString().length(); i += 2) {
55 finalText.setSpan(new ScaleXSpan((spacing + 1) / 10), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
56 }
57 }
58 super.setText(finalText, BufferType.SPANNABLE);
59 }
60
61 public class Spacing {
62 public final static float NORMAL = 0;
63 }
64 }