android忽略特殊字符输入

问题描述:

任何Android专家请帮忙用输入过滤器忽略字符-android忽略特殊字符输入

我成立专班这样做,但所有字符都被忽略.....

public class InputFilterReservedCharacters implements InputFilter { 

    @Override 
    public CharSequence filter(CharSequence source, int start, int end, 
     Spanned dest, int dstart, int dend) { 
     try { 
     if (end > start) { 
      for (int index = start; index < end; index++) { 
       if (source.charAt(index) == "-".toCharArray()[0]) { 
        return ""; 
       } 
      } 
     } 
     } catch (NumberFormatException nfe) { 
     } 
     return ""; 
    } 
} 

感谢StoneBird您有帮助的评论,我想用户除了可以输入任何东西的“ - ”。我得到它的工作是这样的:

@Override 
public CharSequence filter(CharSequence source, int start, int end, 
     Spanned dest, int dstart, int dend) { 

    String returnValue = ""; 

    try { 
     if (end > start) { 
      for (int index = start; index < end; index++) { 
       if (source.charAt(index) != '-'){ 
        returnValue = Character.toString(source.charAt(index)); 
       } 
      } 
     } 
    } catch (NumberFormatException nfe) { 
    } 
    return returnValue; 
} 
+0

通过忽略你的意思,你想从字符串中删除' - '? – wtsang02 2013-04-23 17:19:18

你的代码if (source.charAt(index) == "-".toCharArray()[0]) {return "";}意味着,如果该函数发现-那么函数将返回""作为结果,并从而结束该功能的执行。这就是为什么你每次都会得到空的结果,因为过滤器正在工作,并且正在做你想让它返回的东西。 尝试在函数中创建一个空字符串,将所有“有用”字符连接到该字符串,然后返回该字符串。

public class InputFilterReservedCharacters implements InputFilter { 

@Override 
public CharSequence filter(CharSequence source, int start, int end, 
    Spanned dest, int dstart, int dend) { 
    private CharSequence result = ""; //change here 
    try { 
    if (end > start) { 
     for (int index = start; index < end; index++) { 
      if (source.charAt(index) != "-".toCharArray()[0]) { //change here 
       result+=source.charAt(index); 
      } 
     } 
    } 
    } catch (NumberFormatException nfe) { 
    } 
    return result; //and here 
} 
} 

而且我相信使用'-'而不是双引号给你一个字符,所以你不需要将其转换为字符数组。