如何使用 InputFilter 来限制 Android 中 EditText 中的字符?
我想将字符限制为 0-9、az、AZ 和空格键。设置输入类型我可以限制为数字,但我无法弄清楚输入过滤器浏览文档的方式。
I want to restrict the chars to 0-9, a-z, A-Z and spacebar only. Setting inputtype I can limit to digits but I cannot figure out the ways of Inputfilter looking through the docs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
您可以在正则表达式中指定所需的字符并在 InputFilter 中使用它:
注意,我没有使用
\w
字符类,因为它包含下划线_
You can specify wanted characters in a regex and use it in InputFilter:
Notice, I didn't use
\w
character class, because it includes underscore_
由于某种原因, android.text.LoginFilter 类的构造函数是包范围的,因此您不能直接扩展它(即使它与此代码相同)。但您可以扩展 LoginFilter.UsernameFilterGeneric!然后你就得到了这个:
这并没有真正记录下来,但它是核心库的一部分,并且 源代码很简单。我已经使用它有一段时间了,到目前为止没有任何问题,尽管我承认我还没有尝试过做任何涉及跨度的复杂事情。
For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:
This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.
当我需要阻止用户在 EditText 中输入空字符串时,这个简单的解决方案对我有用。您当然可以添加更多字符:
This simple solution worked for me when I needed to prevent the user from entering empty strings into an EditText. You can of course add more characters:
这是一个旧线程,但专用解决方案都有问题(取决于设备/Android 版本/键盘)。
不同的方法
所以最终我采用了不同的方法,而不是使用
InputFilter
有问题的实现,我使用TextWatcher
和TextChangedListener
。EditText
的完整代码(示例)
InputFilter
在 Android 中不是一个好的解决方案的原因是它取决于键盘实现。在将输入传递到EditText
之前,将对键盘输入进行过滤。但是,由于某些键盘对InputFilter.filter()
调用有不同的实现,因此这是有问题的。另一方面,
TextWatcher
不关心键盘实现,它允许我们创建一个简单的解决方案并确保它适用于所有设备。This is an old thread, but the purposed solutions all have issues (depending on device / Android version / Keyboard).
DIFFERENT APPROACH
So eventually I went with a different approach, instead of using the
InputFilter
problematic implementation, I am usingTextWatcher
and theTextChangedListener
of theEditText
.FULL CODE (EXAMPLE)
The reason
InputFilter
is not a good solution in Android is since it depends on the keyboard implementation. The Keyboard input is being filtered before the input is passed to theEditText
. But, because some keyboards have different implementations for theInputFilter.filter()
invocation, this is problematic.On the other hand
TextWatcher
does not care about the keyboard implementation, it allows us to create a simple solution and be sure it will work on all devices.如果您对 InputFilter 进行子类化,则可以创建自己的 InputFilter 来过滤掉任何非字母数字字符。
InputFilter 接口有一个方法,
filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
,它为您提供有关哪些字符所需的所有信息被输入到它分配给的 EditText 中。创建自己的 InputFilter 后,可以通过调用 setFilters(...) 将其分配给 EditText。
http://developer.android.com/参考/android/text/InputFilter.html#filter(java.lang.CharSequence, int, int, android.text.Spanned, int, int)
If you subclass InputFilter you can create your own InputFilter that would filter out any non-alpha-numeric characters.
The InputFilter Interface has one method,
filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
, and it provides you with all the information you need to know about which characters were entered into the EditText it is assigned to.Once you have created your own InputFilter, you can assign it to the EditText by calling setFilters(...).
http://developer.android.com/reference/android/text/InputFilter.html#filter(java.lang.CharSequence, int, int, android.text.Spanned, int, int)
忽略其他人处理过的跨度内容,为了正确处理字典建议,我发现以下代码有效。
源随着建议的增长而增长,因此我们必须在返回任何内容之前查看它实际上期望我们替换多少个字符。
如果没有任何无效字符,则返回 null 以便进行默认替换。
否则,我们需要从实际要放入 EditText 的子字符串中提取有效字符。
Ignoring the span stuff that other people have dealt with, to properly handle dictionary suggestions I found the following code works.
The source grows as the suggestion grows so we have to look at how many characters it's actually expecting us to replace before we return anything.
If we don't have any invalid characters, return null so that the default replacement occurs.
Otherwise we need to extract out the valid characters from the substring that's ACTUALLY going to be placed into the EditText.
以防止编辑文本中出现单词。
创建一个你可以随时使用的类。
to prevent words in edittext.
create a class that u could use anytime.
可以使用setOnKeyListener。在这个方法中,我们可以自定义输入
edittext
!It is possible to use
setOnKeyListener
. In this method, we can customize the inputedittext
!这就是我在编辑文本中为名称字段创建过滤器的方法。(第一个字母是大写字母,每个单词后只允许有一个空格。
This is how I created filter for the Name field in Edit Text.(First letter is CAPS, and allow only single space after every word.
我在 Kotlin 中有相同的答案:
并使用扩展函数获取类:
I have the same answer in Kotlin:
and get the class with an Extension function:
我在另一个论坛上找到了这个。像冠军一样工作。
I found this on another forum. Works like a champ.
在显示字典建议的 Android 版本中,
InputFilter
有点复杂。有时您会在source
参数中得到一个SpannableStringBuilder
,有时会得到一个普通的String
。以下
InputFilter
应该可以工作。请随意改进此代码!InputFilter
s are a little complicated in Android versions that display dictionary suggestions. You sometimes get aSpannableStringBuilder
, sometimes a plainString
in thesource
parameter.The following
InputFilter
should work. Feel free to improve this code!更容易:
much easier:
发布的答案都不适合我。我有自己的解决方案:
None of posted answers did work for me. I came with my own solution:
使用它可以 100% 满足您的需要,而且非常简单。
在 strings.xml 中
Use this its work 100% your need and very simple.
In strings.xml
为了简单起见,我做了这样的事情:
这样我们就可以用空字符串替换源字符串新部分中的所有不需要的字符。
edit_text
变量是我们引用的EditText
对象。该代码是用
kotlin
编写的。I have done something like this to keep it simple:
This way we are replacing all the unwanted characters in the new part of the source string with an empty string.
The
edit_text
variable is theEditText
object we are referring to.The code is written in
kotlin
.为了避免输入类型中出现特殊字符,
您可以为编辑文本设置过滤器,如下所示
To avoid Special Characters in input type
You can set filter to your edit text like below
首先添加到
strings.xml
:XML:
Kotlin 中的代码:
奇怪,但它在模拟器的软键盘上工作得很奇怪。
警告!以下代码将过滤软件键盘除数字之外的所有字母和其他符号。智能手机上只会出现数字键盘。
我通常还设置
maxLength
、filters
、inputType
。First add into
strings.xml
:XML:
Code in Kotlin:
Strange, but it works weirdly on emulator's soft keyboard.
Warning! The following code will filter all letters and other symbols except digits for software keyboards. Only digital keyboard will appear on smartphones.
I also usually set
maxLength
,filters
,inputType
.除了接受的答案之外,还可以使用例如:
android:inputType="textCapCharacters"
作为
的属性,以便仅接受上限大小写字符(和数字)。In addition to the accepted answer, it is also possible to use e.g.:
android:inputType="textCapCharacters"
as an attribute of<EditText>
in order to only accept upper case characters (and numbers).是的,最好的方法是在 XML 布局本身中修复它:
正如 Florian Fröhlich 正确指出的那样,它甚至适用于文本视图。
请注意,仅显示
android:digits
中提到的字符,因此请小心不要错过任何字符集:)It's Right, the best way to go about it to fix it in the XML Layout itself using:
as rightly pointed by Florian Fröhlich, it works well for text views even.
Just a word of caution, the characters mentioned in the
android:digits
will only be displayed, so just be careful not to miss any set of characters out :)