2015-04-21 164 views
0

我有一个EditText用户必须输入电话号码。电话号码的格式为:^5[4][0-9]{10}$第一个号码是5,第二个号码是4后跟10位数字。Android验证输入,而用户输入

我用下面InputFilter

  InputFilter filter= new InputFilter() { 
       public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
        for (int i = start; i < end; i++) { 
         String checkMe = String.valueOf(source.charAt(i)); 

         Pattern pattern = Pattern.compile("^5[4][0-9]{10}$"); 
         Matcher matcher = pattern.matcher(checkMe); 
         boolean valid = matcher.matches(); 
         if(!valid){ 
          return ""; 
         } 
        } 
        return null; 
       } 
      }; 

尝试,但这个只有充分号相匹配,我想在用户输入数字来验证。

想象一下这样的情况:

User enters 6 -> Does not match the initial digit of the pattern so EditText stays empty 
User enters 5 -> Matches the first digit of the pattern so EditText text = 5 
User enters 3 -> Does not match the second digit of the pattern so EditText text = 5 
User enters 4 -> Matches the second digit of the pattern so EditText text = 54 
From now, if the user adds a digit, EditText will append that until the length of 10 

任何想法,我怎么能做到这一点?

回答

0

使用TextWatcher接口

XML限制输入类型(编号)和max字符(12)

<EditText 
     .... 
     android:inputType="number" 
     android:maxLength="12" > 

爪哇

editText.addTextChangedListener(new PhoneNumberTextWatcher()); 

TextWatcher接口

class PhoneNumberTextWatcher implements TextWatcher { 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 
      if (s != null && s.length() > 0) { 
       String number = s.toString(); 
       if (number.startsWith("5")) { 
        if (number.length() > 1) 
         if (!number.startsWith("54")) { 
          editText.setText("5");//if second number is not 4 
          editText.setSelection(editText.length()); // move the cursor to 1 position 
         } 

       } else 
        editText.setText(""); 
      } 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    } 

Happy_Coding .... :)

+0

是的。谢谢。解决了。 – Favolas