問題描述
有沒有一種方法可以為 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 小部件的屏蔽輸入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!