1

In android edit text, how to separate 10 digit number input by space? I am using android text watcher and I am trying to input multiple 10 digit numbers in the field. The issue arises when multiple numbers are copied and pasted in the field and that time, it doesn't take those spaces. Kindly let me know a solution in order to allow multiple number input with a space after every 10 digit number, when the number is copied from other place.

Sne
  • 13
  • 7
  • what happens when you paste the number? – Vladyslav Matviienko Aug 14 '18 at 07:10
  • please post what you have done? – Saurabh Vadhva Aug 14 '18 at 07:11
  • How will you be sure, the number is having 10 digits, what if it has country code prefix? – Khemraj Sharma Aug 14 '18 at 07:22
  • duplication - https://stackoverflow.com/questions/10252757/android-format-edittext-to-display-spaces-after-every-4-characters – Arnold Brown Aug 14 '18 at 07:37
  • afterTextChanged(Editable s){if (s.length() > 0&&(s.length() %11)==0){final char c = s.charAt(s.length() - 1);if (space == c{s.delete(s.length() - 1,s.length()); i did this in Textwatcher } } if (s.length() > 0 && (s.length() % 11) == 0) { char c = s.charAt(s.length() - 1); if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 10) { s.insert(s.length() - 1, String.valueOf(space)); } } } – Sne Aug 14 '18 at 08:21

2 Answers2

1

This will work for both type and copy/paste from other place.

yourEditText.addTextChangedListener(new TextWatcher() {
        private static final char space = ' ';

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {

            int pos = 0;
            while (true) {
                if (pos >= s.length()) break;
                if (space == s.charAt(pos) && (((pos + 1) % 11) != 0 || pos + 1 == s.length())) {
                    s.delete(pos, pos + 1);
                } else {
                    pos++;
                }
            }
            pos = 10;
            while (true) {
                if (pos >= s.length()) break;
                final char c = s.charAt(pos);
                if (Character.isDigit(c)) {
                    s.insert(pos, "" + space);
                }
                pos += 11;
            }
        }
    });
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53
1

Edit and Use the following code as per your needs

StringBuilder s;
s = new StringBuilder(yourTxtView.getText().toString());

for(int i = 10; i < s.length(); i += 10){
s.insert(i, " "); // this line inserts a space
}
yourTxtView.setText(s.toString());

and when you need to get the String without spaces do this:

String str = yourTxtView.getText().toString().replace(" ", "");
amit
  • 709
  • 6
  • 17