本文介紹了在 EditText 中僅允許基于正則表達式的選定字符的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我希望僅允許用戶根據(jù)我的 android 應(yīng)用程序中的正則表達式鍵入某些字符.如何實現(xiàn)?
I want to allow users only to type certain characters based on the a regex in my android applications. How do I achieve it?
推薦答案
按照@Matt Ball 的建議使用 TextWatcher
.
Used a TextWatcher
as @Matt Ball suggested.
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int length = text.length();
if(length > 0 && !Pattern.matches(PATTERN, text)) {
s.delete(length - 1, length);
}
}
編輯雖然 TextWatcher
可以工作,但使用 InputFilter
會更簡潔.檢查此示例.
Edit
Although the TextWatcher
works, it would be cleaner to use an InputFilter
. Check this example.
這篇關(guān)于在 EditText 中僅允許基于正則表達式的選定字符的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!