2014-09-27 86 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; 
}