在android中需要在EditView中输入电话号码3 + 4 + 4格式时,以下两种方式都可以实现,但是个人觉得第一种方式,即获取EditView文字内容变化是最好的方式。所谓3+4+4的电话号码格式,如:135 4567 8900
第一种:捕捉EditView的内容改变
et_PhoneNum.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) { // 已经改变了的。 String contents = str.toString(); int length = contents.length(); if(length == 4){ if(contents.substring(3).equals(new String(" "))){ // - contents = contents.substring(0, 3); et_PhoneNum.setText(contents); et_PhoneNum.setSelection(contents.length()); }else{ // + contents = contents.substring(0, 3) + " " + contents.substring(3); et_PhoneNum.setText(contents); et_PhoneNum.setSelection(contents.length()); } } else if(length == 9){ if(contents.substring(8).equals(new String(" "))){ // - contents = contents.substring(0, 8); et_PhoneNum.setText(contents); et_PhoneNum.setSelection(contents.length()); }else{// + contents = contents.substring(0, 8) + " " + contents.substring(8); et_PhoneNum.setText(contents); et_PhoneNum.setSelection(contents.length()); } } } @Override public void beforeTextChanged(CharSequence str, int arg1, int arg2,int arg3) { } @Override public void afterTextChanged(Editable arg0) {// TODO Auto-generated method stub } });这里只罗列了主要的逻辑代码,这个EditView的inputType是phone。其它的就不用多说了,布局上的事情。
第二种:捕获EditText的onKeyDown和onKeyUp事件,分别进行处理,但是在搜狗软键盘上,按数字的时候不能响应onKeyUp。有点bug,相比之下,还是第一种方式最好。
et_PhoneNum.setOnKeyListener(new MyEditTextOnKeyListener());
class MyEditTextOnKeyListener implements OnKeyListener{ @Override public boolean onKey(View arg0, int code, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN){ if(code == KeyEvent.KEYCODE_DEL){ String phoneNum2 = et_PhoneNum.getText().toString() ; int length2 = phoneNum2.length() ; if(length2 == 5){ phoneNum2 = phoneNum2.substring(0, 3); et_PhoneNum.setText(phoneNum2); et_PhoneNum.setSelection(phoneNum2.length()); return true; }else if(length2 == 10){ phoneNum2 = phoneNum2.substring(0, 8); et_PhoneNum.setText(phoneNum2); et_PhoneNum.setSelection(phoneNum2.length()); return true; } return false; } } if(event.getAction() == KeyEvent.ACTION_UP){ // must caught key up String phoneNum = et_PhoneNum.getText().toString() ; Log.e("ACTION_UP"," code = " + code); Log.e("ACTION_UP"," phoneNum = " + phoneNum); if(phoneNum.equals("")){ return false ; } int length = phoneNum.length() ; if(length == 4){ phoneNum = phoneNum.substring(0, 3) + " " + phoneNum.substring(3, 4); et_PhoneNum.setText(phoneNum); et_PhoneNum.setSelection(phoneNum.length()); } if(length == 9){ phoneNum = phoneNum.substring(0, 8) + " " + phoneNum.substring(8, 9); et_PhoneNum.setText(phoneNum); et_PhoneNum.setSelection(phoneNum.length()); } } return false; } }