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.
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.
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With