隻允許edittext輸入數字或者email格式字元是非常簡單的(詳見api文檔)。
要實作隻允許輸入自定的數字字元也是很容易的(詳見api文檔,setkeylistener(keylistener)
和setfilters (inputfilter[] filters) )。
但是要限制隻能輸入指定的字母字元就非常的困難。
/**
inputfilter[] ifs = {new inputfilter.lengthfilter(10),new digitskeylistener(true,true)};
edittext01.setfilters(ifs);
**/
發現,android:digits的參數是一個字元串,沒有更多的語義檢查,是以想到内部處理很可能僅是簡單的檢查,輸入的字元是否在給定的字元串中(要我設計,我就這樣做)。嘗試着給它指定帶有英文字元的參數,發現果然如此。萬幸,萬幸!
在layout.xml裡
xml代碼
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5Sew92Yf52bjl2LcNXZnFWbp9CXt92Yu4Wd5lGbh5iclB3bsVmdlR2Lc9CX6MHc0RHaiojIsJye.gif)
<edittext
android:id="@+id/register_username_edittext"
style="@style/register_edittext_style"
android:digits="@string/register_name_digits"
android:textcolor="@drawable/register_edit_text_textcolor"
android:textcolorhint="@drawable/register_hint_text_textcolor"
android:hint="@string/register_name_hint_text"
/>
在string.xml裡
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5Sew92Yf52bjl2LcNXZnFWbp9CXt92Yu4Wd5lGbh5iclB3bsVmdlR2Lc9CX6MHc0RHaiojIsJye.gif)
<string name="register_name_digits">
._0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklimnopqrstuvwxyz
</string>
另外:
java代碼
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5Sew92Yf52bjl2LcNXZnFWbp9CXt92Yu4Wd5lGbh5iclB3bsVmdlR2Lc9CX6MHc0RHaiojIsJye.gif)
edittext01.addtextchangedlistener(new textwatcher() {
string tmp = "";
string digits = "abcdef";
@override
public void ontextchanged(charsequence s, int start, int before, int count) {
}
public void beforetextchanged(charsequence s, int start, int count, int after) {
tmp = s.tostring();
public void aftertextchanged(editable s) {
log.d(sample4main.tag, "<><>aftertextchanged<><>" + s.tostring());
string str = s.tostring();
if(str.equals(tmp)){
return;
}
stringbuffer sb = new stringbuffer();
for(int i = 0; i < str.length(); i++){
if(digits.indexof(str.charat(i)) >= 0){
sb.append(str.charat(i));
}
tmp = sb.tostring();
edittext01.settext(tmp);
});