Vishwa Vishwa - 5 months ago 61
Android Question

Format edittext as xxx-xx-xxxx in android

am developing an simple application.In which EditText get number input from user.i want to display the number in XXX-XX-XXXX format instead of XXXXXXXXX format.is there any way to achieve it..Thanks in advance.....

Answer

After long time i got it by using this code.

fix the lines in edittext xml

android:maxLength="11"

now try this code

    final EditText edittext = (EditText) findViewById(R.id.editText4);
    edittext.addTextChangedListener(new TextWatcher() {
        int cursorPosition = 0;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            edittext.removeTextChangedListener(this);

            try {
                cursorPosition = edittext.getSelectionStart();
                if (editable.length() > 0) {

                    String tempIp = "";
                    String newIp = "";
                    String strIp = edittext.getText().toString();
                    String tempParamArr[] = strIp.split("-");
                    if (tempParamArr.length > 0) {
                        cursorPosition -= (tempParamArr.length - 1);
                        for (int i = 0; i < tempParamArr.length; i++) {
                            tempIp += tempParamArr[i];
                        }
                    } else {
                        tempIp = strIp;
                    }

                    for (int count = 0; count < tempIp.length(); count++) {
                        if (count == 3 || count == 5) {
                            newIp += "-";
                            newIp += tempIp.charAt(count);
                            cursorPosition++;
                        } else {
                            newIp += tempIp.charAt(count);
                        }
                    }
                    edittext.setText(newIp);
                    if (newIp.length() > cursorPosition)
                        edittext.setSelection(cursorPosition);
                    else
                        edittext.setSelection(newIp.length());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            edittext.addTextChangedListener(this);

        }
    });
Comments