在android中输入第一个字符后立即输入字符 [英] Enter character immediately after entering first character in android
问题描述
我有一个editText和inputType作为电话号码.输入第一个数字后,我想立即添加特定的区号.例如说
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
我输入6,EditText应该显示为+16.
I enter 6 the EditText should show up +1 6.
我正在尝试使用textWatcher实现此目的,但不确定如何将输入的数字放在"+1"之后
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());
}
}
但是这里的问题是,当我输入第一个数字时,会填充+1,但不会显示通过键盘键入的数字.我不确定这里出什么问题了吗?
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?
当我退格并从文本中删除1时,也会发生这种情况,但是我无法删除+(这会自动填充).当我在填充+1后退格时,我不想删除+1.
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.
有可能吗?
谢谢!
推荐答案
要输入+1之后的下一个字符,您应该使用:
For input the next character after the +1 you should use :
numberText.settext("+1" + s.toString());
要向后退+1,您需要keyListener :(不适用于软键盘)
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());
}
}
这篇关于在android中输入第一个字符后立即输入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!