如何限制 Android 中的 TextView 仅允许字母数字字符
我的应用程序中有一个 TextView,我希望用户只能在其中输入字母数字字符。如何做到这一点?谢谢!
I have a TextView in my app that i want a user to be able to only enter alpha-numeric characters in. How can this be done? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 XML 中,输入以下内容:
In the XML, put this:
这是一个更好的解决方案...... https://groups.google.com/forum/?fromgroups=#!topic/android-developers/hS9Xj3zFwZA
Here is a better solution......... https://groups.google.com/forum/?fromgroups=#!topic/android-developers/hS9Xj3zFwZA
InputFilter
解决方案运行良好,让您可以完全控制以比android:digits
更细的粒度过滤输入。如果所有字符都有效,则filter()
方法应返回null
;如果某些字符无效,则应返回仅包含有效字符的CharSequence
。如果复制并粘贴了多个字符,并且其中一些字符无效,则应仅保留有效字符(如果任何字符无效,@AchJ 的解决方案将拒绝整个粘贴)。另外,在设置
InputFilter
时,必须确保不要覆盖EditText
上设置的其他InputFilters
;这些可以在 XML 中设置,例如android:maxLength
。您还必须考虑InputFilters
设置的顺序。当与长度过滤器结合使用时,您的自定义过滤器应插入到长度过滤器之前,这样粘贴的文本会在长度过滤器之前应用自定义过滤器(@AchJ 的解决方案将覆盖所有其他InputFilters
并且仅应用自定义的)。The
InputFilter
solution works well, and gives you full control to filter out input at a finer grain level thanandroid:digits
. Thefilter()
method should returnnull
if all characters are valid, or aCharSequence
of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept (@AchJ's solution will reject the entire paste if any characters a invalid).Also, when setting your
InputFilter
, you must make sure not to overwrite otherInputFilters
set on yourEditText
; these could be set in XML, likeandroid:maxLength
. You must also consider the order that theInputFilters
are set. When used in conjunction with a length filter, your custom filter should be inserted before the length filter, that way pasted text applies the custom filter before the length filter (@AchJ's solution will overwrite all otherInputFilters
and only apply the custom one).这应该有效:
This should work: