1

我有在 EditText 中输入电话号码的规定。我想确保用户以 +91+电话号码的格式输入电话号码。即,如果用户输入第一个字符,请检查它是否为“+”,然后添加到EditText else not.like this 我想检查前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) {

            }
        });

提前致谢

4

2 回答 2

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{

             }

        }
    });
于 2013-03-27T10:09:06.583 回答
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.
于 2013-03-27T10:10:32.263 回答