Search code examples
androidandroid-studioandroid-layoutandroid-widget

How to make {EditText} accept input in format:


Car number plate(Registration number) - 2chars-2digit-2chars-4chars

I tried this resource with some modification Custom format edit text input , but unfortunately I was unable to delete the Hyphen(-). Whenever there is a Hyphen(-), I could not to delete it. Please help me in finding out the issue.


Solution

  • You are unable to delete hyphen because in ontextchanged, when you get to the hyphen character position, you are again adding the hyphen.

    You should differentiate if you got to hyphen character by adding the text or by deleting the text.

    If you got to the hyphen position by deleting text, you dont want to add hyphen.

    You can check by this code if(before-count<0){

    Below is your working example

         editText.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    
                    if ((editText.getText().length() + 1 == 3 || editText.getText().length() + 1 == 6 || editText.getText().length() + 1 == 9)) {
                        if(before-count<0){
                            editText.setText(editText.getText() + "-");
                            editText.setSelection(editText.getText().length());
                        }
                    }
                }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }
    
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });
    }
    

    }

    XML

     android:maxLength="13"