2014-09-27 92 views
1

使用輸入濾波器的EditText特定字符我有我如下樹立了一個輸入濾波器一個EditText:允許機器人

filter_username = new InputFilter() { 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
       boolean keepOriginal = true; 
       StringBuilder sb = new StringBuilder(end - start); 
       for (int i = start; i < end; i++) { 

        char c = source.charAt(i); 

        if (isCharAllowed2(c)) // put your condition here 
         sb.append(c); 
        else 
         keepOriginal = false; 
       } 
       if (keepOriginal) 
        return null; 
       else { 
        if (source instanceof Spanned) { 
         SpannableString sp = new SpannableString(sb); 
         TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0); 
         return sp; 
        } else { 
         return sb; 
        }   
       } 
      } 

      private boolean isCharAllowed2(char c) { 
       return Character.isLetterOrDigit(c); 

      } 

}; 

txtusername.setFilters(new InputFilter[]{filter_username}); 

的問題是我想要做如下修改上面的過濾器:

1)第一個字符應該是數字 2)下劃線和點是唯一的字符允許

你能告訴我如何修改上面的過濾器,以滿足我的要求?

編輯: 我想通了特殊字符部分由以下變化:

private boolean isCharAllowed2(char c) { 
       return Character.isLetterOrDigit(c)||c=='_'||c=='.'; 

      } 

如何防止從一個數字或一個時期的第一個字符?

回答

0

Character.isLetterOrDigit檢查,如果指定的字符是字母或digit.so使用Character.isLetter其返回true如果字符是字母,否則false

private boolean isCharAllowed2(char c) { 
     if(sb.length()==0) 
      return Character.isLetter(c); 
     else 
      return Character.isLetterOrDigit(c); 

    } 
+0

但是我可以接受來自第二個字符的數字。我想對edittext中的第一個字符進行驗證。我不想讓它以數字開頭。 – 2014-09-27 11:43:37

+0

@AchuthanM:看到我的編輯答案 – 2014-09-27 11:49:26

+0

沒有工作..... – 2014-09-27 11:52:28

0

這是你應該使用哪一個做你的要求是什麼功能,建築從你已經發現:

1我如何防止第一個字符是一個數字或一段時間?
2下劃線和點唯一的字符允許

private boolean isCharAllowed2(char c, final int position) { 
    if(position == 0) // 0 position in your string 
     return ! (Character.isDigit(c) || c=='.'); // point 1 
    else 
     return Character.isLetterOrDigit(c)|| c=='_'|| c=='.'; // point 2 
} 

您在調用它在你的代碼迴路(我從以前的,你的意思是字母+數字+下劃線+期編輯假設):

for (int i = start; i < end; i++) { 
    char c = source.charAt(i); 

    if (isCharAllowed2(c, i)) // this passes the position of the character to your isCharAllowed2 function, allowing you to decide on the filtering there according to the position in the String 
     sb.append(c); 
    else 
     keepOriginal = false; 
}