我可以在EditText中输入电话号码。我想确保用户输入格式为+ 91 +电话号码的电话号码。如果用户输入第一个字符,请检查是否为'+ '然后添加到EditText其他没有。像这样我想检查前3个字符。怎么做?
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
String phNum = charSequence.toString();
if(phNum.trim() .length() > 0 ){
int length = phNum.trim().length();
switch (length) {
case 1:
if(phNum.substring(0) != null && !phNum.substring(0).equals("+")){
editText.setText("");
}
break;
case 2:
if(phNum.substring(0,2) != null && !phNum.substring(0,2).equals("+9")){
editText.setText(phNum.substring(0,1));
}
break;
case 3:
if(phNum.substring(0,3) != null && !phNum.substring(0,3).equals("+91")){
editText.setText(phNum.substring(0,2));
}
break;
default:
break;
}
Toast.makeText(CallFilterActivity.this, "Enter +91 before number", Toast.LENGTH_SHORT).show();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
先谢谢
答案 0 :(得分:0)
您可以使用TextWatcher
侦听器。
例如
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if(isFirstCharacter){
//check if the character is + and add
}else{
}
}
});
答案 1 :(得分:0)
Use something like this:
editText.addTextChangedListener(this);
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stug
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
Check for the entered character and then allow further typing or display an alert.