Letter Spacing In Android Edittext
I am trying to Display a text box with letters separated by spaces. EditText wordText = (EditText) findViewById(R.id.word_text); wordText.setPaintFlags(wordText.getPaintFla
Solution 1:
The subject of letter spacing seems to have caused quite some traffic over the years. Some preach for using textScaleX
property, but that by itself is not an acceptable solution, because it skews the letters as well. Several other solutions that were mentioned are:
- Create a custom font and add you own spacing there. It is convoluted though, because it involves copyright and not-so-dynamic spacing between letters
- Adding spaces in between letters - also not so desirable, because there is not enough granularity when it comes to increases in spacing values
- A combination of
textScaleX
and adding spaces between letters - it involves a custom view wheretextScaleX
is applied only to the spaces - so the letters remain unchanged, only the space increases-decreases. You can use the non breakable space unicode character as well. For this solution you can check out Change text kerning or spacing in TextView?
Solution 2:
Make TextWatcher (this example for enter only digits into EditText field, you can change it if necessary)
publicclassCustomTextWatcherimplementsTextWatcher{ privatestaticfinalcharspace=' '; publicCodeTextWatcher(){} @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) { } @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) { } @OverridepublicvoidafterTextChanged(Editable s) { // Remove all spacing charintpos=0; while (true) { if (pos >= s.length()) break; if (space == s.charAt(pos) && (((pos + 1) % 2) != 0 || pos + 1 == s.length())) { s.delete(pos, pos + 1); } else { pos++; } } // Insert char where needed. pos = 1; while (true) { if (pos >= s.length()) break; finalcharc= s.charAt(pos); // Only if its a digit where there should be a space we insert a spaceif ("0123456789".indexOf(c) >= 0) { s.insert(pos, "" + space); } pos += 2; } }
}
Attach this textWatcher to your EditText:
EditText.addTextChangedListener(newCustomTextWatcher());
Post a Comment for "Letter Spacing In Android Edittext"