EditText is used to display large numbers. How to separate every three digits of the number with a space? For example 9 999 999

    2 answers 2

    You can do this with TextWatcher .

    For example, you can use the ready-made PhoneNumberFormattingTextWatcher class, which implements the TextWatcher interface, to format phone numbers:

     EditText inputField = (EditText) findViewById(R.id.inputfield); inputField.addTextChangedListener(new PhoneNumberFormattingTextWatcher()); 

    As a result, the entered text +375298076740 will look like

    +375 29 807-67-40

    If you need to display the text in groups of three characters, you can use the following class:

     public class OwnWatcher implements TextWatcher { // Change this to what you want... ' ', '-' etc.. private static final char space = ' '; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // Remove spacing char if (s.length() > 0 && (s.length() % 4) == 0) { final char c = s.charAt(s.length() - 1); if (space == c) { s.delete(s.length() - 1, s.length()); } } // Insert char where needed. if (s.length() > 0 && (s.length() % 4) == 0) { char c = s.charAt(s.length() - 1); // Only if its a digit where there should be a space we insert a space if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) { s.insert(s.length() - 1, String.valueOf(space)); } } } } 

    And assign it to a specific field:

     inputField.addTextChangedListener(new OwnWatcher()); 

    The output will be as in the picture:

    enter image description here

    • It looks very good and simple, but for some reason it does not work = (The class created the same. In the fragment in onCreateView, the listener assigned. But it does not work. - Alexander Tymchuk
    • And what mistakes gives? - Ksenia
    • Without mistakes, just the text as usual remains - Alexander Tymchuk
    • Maybe put a link to the project? - Alexander Tymchuk

    Override the onDraw method.

    In it to make logic that will add / remove a space.

    Perhaps there are better ways to realize this.