Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append text at beginning of edittext [duplicate]

How to automatically add a text at beginning of edittext as soon as user start typing in it.For example I want to automatically append country code as soon as user start typing phone number. I tried-

      mNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
            mNumber.setText("+91"+editable.getText().toString());
            }
        });

But this doesn't worked and my device hangs as soon as i type in the edittext.

like image 774
Android Developer Avatar asked Dec 04 '22 00:12

Android Developer


2 Answers

You're causing an infinite loop because you're calling setText() from afterTextChanged(), then setText() is calling afterTextChanged() and so on and so forth.

you can change your afterTextChanged() to the following,

public void afterTextChanged(Editable s) {
    if(!s.toString().startsWith("+91")){
        s.insert(0, "+91");
    }
}

This way you're not calling setText() all the time, also the check is there so that you're not adding "+91" each time the user types something in the EditText. One drawback to this method is that you can't delete the "+91" by backspace, once its been automatically inserted at the beginning of the input.

like image 165
wanpanman Avatar answered Jan 27 '23 20:01

wanpanman


Your app hangs, because mNumber.setText("...") triggers your addTextChangedListener() again, and again, and again...

You can avoid that by checking if the prefix is already set and only prepending the prefix if it is not.

public void afterTextChanged(Editable editable) {
    if (!mNumber.getText().startsWith("+91")) {
        mNumber.setText("+91"+mNumber.getText());
    }
}
like image 43
Ridcully Avatar answered Jan 27 '23 18:01

Ridcully