Enter character immediately after entering first c

2019-09-16 08:28发布

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!

4条回答
倾城 Initia
2楼-- · 2019-09-16 08:30

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());
  }
}
查看更多
别忘想泡老子
3楼-- · 2019-09-16 08:40

Replace

numberText.settext("+1");

With

numberText.settext("+1"+s.toString());
查看更多
我只想做你的唯一
4楼-- · 2019-09-16 08:45

Replace

numberText.settext("+1");

with

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

You are not updating the existing text properly.

查看更多
迷人小祖宗
5楼-- · 2019-09-16 08:48

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

查看更多
登录 后发表回答