Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add character automatically in EditText after 6 letters

I want to automatically put a "-" after 6 letters in my EditText and I want the user can continue to write after the "-". (I want the user writes : 1234562 and it appears 123456-2 in the EditText).

But I don't know how to do this and if it is possible. If you can help me, thanks

like image 906
odiiil Avatar asked Jul 25 '14 12:07

odiiil


2 Answers

Add a textwatcher.Then use the following code:

@Override
public void afterTextChanged(Editable text) {     


    if (text.length() == 6) {
        text.append('-');
    }


}

You can also use multiple condition in the if statement like:

 if (text.length() == 3 || text.length() == 6) {
        text.append('-');
    }
like image 190
kgandroid Avatar answered Sep 18 '22 08:09

kgandroid


you can also delete characters with this:

text.addTextChangedListener(new TextWatcher() {
        int first = 0;
        int second;

        @Override
        public void afterTextChanged(Editable s) {
            second = first;
            first = s.length();

            if(text.length()==6 && first>second){
                text.append("-");
            }
        }
like image 43
Erald Haka Avatar answered Sep 20 '22 08:09

Erald Haka