Prepend in an Edittext using Textwatcher

Asked

Viewed 61 times

1

How to make a prepend on Android?

Currently I do some append, but I didn’t see how to make a prepend at the event onTextChanged.

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

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

1 answer

1


Use the method afterTextChanged() textwatcher:

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

Should you want the ( is 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, "(");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.