在 Android 中使用 EditText 小部件的屏蔽输入 [英] Masked Input Using EditText Widget in Android

查看:26
本文介绍了在 Android 中使用 EditText 小部件的屏蔽输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以为 Android 中的 EditText 控件指定输入掩码?

Is there a way I can specify an input mask to the EditText control in Android?

我希望能够为社会安全号码指定类似 ### - ## - #### 的内容.这将导致自动拒绝任何无效输入(例如,我输入字母字符而不是数字).

I want be able to specify something like ### - ## - #### for a Social Security Number. This will cause any invalid input to be rejected automatically (example, I type alphabetical characters instead of numeric digits).

我意识到我可以添加一个 OnKeyListener 并手动检查有效性.但这很乏味,我将不得不处理各种边缘情况.

I realize that I can add an OnKeyListener and manually check for validity. But this is tedious and I will have to handle various edge cases.

嗡嗡声

推荐答案

尝试使用 InputFilter 而不是 OnKeyListener.这意味着您不必担心跟踪单个按键,它还可以处理诸如粘贴到字段中之类的事情,而使用 OnKeyListener 来处理这些事情会很痛苦.

Try using an InputFilter rather than an OnKeyListener. This means you don't have worry about tracking individual key presses and it will also handle things like pasting into a field which would be painful to handle with an OnKeyListener.

你可以看看 Android 附带的 InputFilter 实现的源代码,为您提供编写自己的起点.

You could have a look at the source of the InputFilter implementations that come with Android to give you a starting point for writing your own.

这篇关于在 Android 中使用 EditText 小部件的屏蔽输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆