【问题标题】:Block input if it's not the letter "A" [duplicate]如果不是字母“A”,则阻止输入[重复]
【发布时间】:2013-03-13 17:43:01
【问题描述】:

如果用户没有输入A,我该怎么做,那么不会有任何输出?我想在EditText 中执行此操作。

代码:

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++) { 
                            if (!Character.toString(source.charAt(i)).equals("a")) { 
                                    return ""; 
                            } 
                    } 
                    return null; 
            } 
        }; 

【问题讨论】:

  • 到目前为止你有什么?
  • 我尝试了 InputFilter 的一些东西,但它不起作用..
  • @BartWesselink 无需输入 EditText 中的字符
  • 但是当它不是 a 时,你怎么能阻止它呢?
  • @BartWesselink 现在我明白你了,发布你的代码

标签: android android-edittext


【解决方案1】:

您可以使用输入过滤器按照您尝试的方式执行此操作,但我建议您改为使用 XML 执行此操作,方法是为您的 edittext 提供属性android:digits="Aa"。这应该可以解决您的问题。

如果你需要使用输入过滤器,试试这个(它未经测试,可能不会比你的更好)

InputFilter filter = new InputFilter() { 
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
                    String chars = "";
                    for (int i = start; i < end; i++) { 
                            if (Character.toString(source.charAt(i)).equals("a")) { 
                                    chars = chars + source.charAt(i);
                            } else {
                                //don't add anything to the char sequence
                            }
                    } 
                    return chars; 
            } 
        }; 

【讨论】:

  • A 是例如,它总是另一个字母。对不起
  • @BartWesselink - 试试我添加的代码,它可能会工作
  • 呵呵,不行。。(在模拟器中我用的是笔记本的键盘)
  • @BartWesselink - 我更新了代码,什么不起作用?
  • 没有。我不明白为什么它不起作用...
猜你喜欢
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2017-11-18
  • 2020-11-30
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多