Prepend on an EditText using TextWatcher

1

How to make a prepend on Android?

I currently do some append , but did not see how to do a prepend in the onTextChanged event.

The reason is to put a ( before the first 2 digits of a phone, to get the (xx) x xxxx - xxxx mask.

That is, this ( would be entered after the user entered the first digit but before it.

    
asked by anonymous 30.05.2017 / 20:37

1 answer

1

Use the method afterTextChanged() of TextWatcher:

@Override
public void afterTextChanged(Editable editable) {
    if(editable.length() == 1 && !editable.toString().equals("(")){
        editable.insert(0, "(");
    }
}

If you want ( to be deleted when the first number is deleted, use:

@Override
public void afterTextChanged(Editable editable) {
    if(editable.toString().equals("(")){
        editable.clear();
        return;
    }
    if(editable.length() == 1) {
        editable.insert(0, "(");
    }
}
    
30.05.2017 / 22:39