Enter character immediately after entering first c

2019-09-16 07:51发布

问题:

I am having a editText and inputType as phone number. I would like add specific area code immediately after I enter first digit. Say for example

I enter 6 the EditText should show up +1 6.

I am trying achieve this using textWatcher but not sure how to put the number that I type after "+1"

   public void afterTextChanged(Editable s) 
            {               
                if(s.length() == 1)
                {
                    numberText.settext("+1");
                    numberText.setSelection(numberText.getText().length());
                }
            }

But the problem here is that when I enter first number the +1 is populated but the number which type through keyboard is not getting shown. I am not sure what is wrong here?

Also when I backspace and remove 1 from the text this happens but I am not able to remove + (this populates automatically). I don't want to remove +1 when I back space after +1 is populated.

Is this possible, if so how?

Thanks!

回答1:

For input the next character after the +1 you should use :

numberText.settext("+1" + s.toString());

For backspace the +1 you need keyListener : (not worked with soft keyboard)

numberText.setOnKeyListener(new OnKeyListener() {                 
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            //You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
             if(keyCode == KeyEvent.KEYCODE_DEL){  
                 //this is for backspace
                 String text = numberText.getText().toString();
                 if(text.equals("+1")) 
                   return false; 
             }      
        }
    });

EDIT
Trying to hack approach :

public void afterTextChanged(Editable s) 
{               
  if(s.length() == 0 || s.toString().equals("+"))
  {
    numberText.settext("+1");
  }
  else if(s.length() == 1)
  {
    numberText.settext("+1"+s.toString());
    numberText.setSelection(numberText.getText().length());
  }
}


回答2:

Replace

numberText.settext("+1");

with

numberText.settext("+1" + s.toString());

You are not updating the existing text properly.



回答3:

Use this:

public void afterTextChanged(Editable s) 
        {               
            if(s.length() == 1)
            {
                String text = numberText.getText().toString();
                numberText.settext("+1"+text);
                numberText.setSelection(numberText.getText().length());
            }
        }

other is alright may be



回答4:

Replace

numberText.settext("+1");

With

numberText.settext("+1"+s.toString());