Chandan Wadhwa
Chandan Wadhwa

Reputation: 196

Append "@gmail.com" in EditText after pressing any key from user in android

I am thinking the logic as given below

editTextUserName.addTextChangedListener(new TextWatcher() {
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {

       }    
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {

   }    
   @Override
   public void afterTextChanged(Editable s) {
                appendEmail(editTextUserName.getText().toString());
            }
        });    
 void appendEmail(String email){
        if( email.length()>=1){

            editTextUserName.setText("@gmail.com");
    }
}

This is example code not the actual code. This is throwing the stackoverflow exception.

Can anyone resolve the isssue

Upvotes: 1

Views: 185

Answers (3)

Don Chakkappan
Don Chakkappan

Reputation: 7560

I think TextWatcher is not appropriate here (as m vai commented).

Do something like in your EditText tag add android:imeOptions="actionDone"

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
         editText.setText(editText.getText().toString()+"@gmail.com");  
        }
        return false;
    }
});

Upvotes: 2

natario
natario

Reputation: 25194

Didn't test, but I fear afterTextChanged() gets called after each letter you type. If this is the case, you should try other callbacks, like losing focus:

mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    onFocusChange(View v, boolean hasFocus) {
        EditText edit = (EditText) v;
        String text = edit.getText().toString();
        if (!hasFocus && text.length() > 0) {
            edit.setText(text + "@gmail.com");
        }
    }
})

Upvotes: 0

Ilya Vorobiev
Ilya Vorobiev

Reputation: 836

You need to check if the substring "@gmail.com" is already exists there is no need to setText again. Because when you set text to EditText it calls afterTextChange again, and then you call appendEmail and then it sets text again etc.

void appendEmail(String email){
      if(!TextUtils.isEmpty(email) && email.contains("@gmail.com")){

            editTextUserName.setText(email + "@gmail.com");
      }

Upvotes: 2

Related Questions