2

I am working on EdituserProfileActivity in which I have to enter the user's height in EditText like (5'6)(5'11)(feet'inch.) etc. Now when I enter the first character in EditText, a single apostrophe ' is automatically added to (onTextChanged) at the second position of EditText.

The problem is that when I try to erase characters, it will not erase after the first position because when EditText length is 1, it will add a ' at the second position.

How can I fix this? Please share any solutions with me.

And sorry for my bad English

   edtUserHeight.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {


        }

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

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

            int len=edtUserHeight.getText().toString().length();

            if(len==1)
            {
                edtUserHeight.setText(edtUserHeight.getText()+"'");
                edtUserHeight.setSelection(edtUserHeight.getText().length());
            }
            else{

            }

        }
    });
Jon
  • 2,502
  • 4
  • 21
  • 23
Manu Garg
  • 186
  • 2
  • 13

1 Answers1

0

I believe you are looking for a check like this:

if (before == 1 && s.length() == start) {
    return; // allows delete
}

This will allow you to perform a pass-through in the operation. So your code would look like this:

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

        String height = edtUserHeight.getText().toString();

        if(height.length() == 1) {
             edtUserHeight.setText(height + "'");
        }

        if (before == 1 && s.length() == start) {
            return; // allows delete
        }else{
            edtUserHeight.setSelection(height.length());
        }
    }

For more information on what before and start parameters mean, check out this answer.

DummyData
  • 645
  • 9
  • 14