經過許多失敗的嘗試,以實現輸入過濾或正則表達式,我選擇了一些更直截了當:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String a = "";
String str = id.getText().toString();
String replaced = str.replaceAll(Pattern.quote("."),"");
replaced = replaced.replaceAll(Pattern.quote("-"),"");
char[] id_char = replaced.toCharArray();
int id_len = replaced.length();
for(int i = 0; i < id_len; i++) {
if(i == 2 || i == 12) {
a += id_char[i] + ".";
}
else if (i == 5 || i == 9) {
a += id_char[i] + "-";
}
else a += id_char[i];
}
id.removeTextChangedListener(this);
id.setText(a);
if(before > 0) id.setSelection(start);
else id.setSelection(a.length());
id.addTextChangedListener(this);
}
我不知道這是不是最好的方法,但它確實工作。我仍然沒有解決的一個問題是如何在用戶刪除或插入數字後處理光標放置。如果用戶在EditText的某處插入光標並輸入一個新數字,則光標跳轉到EditText的末尾。我希望光標保持在它所在的位置。另一個問題是,如果用戶在EditText編號和退格鍵中插入光標以刪除編號,則第一個鍵輸入不起作用,第二個鍵輸入編號。我只能猜測這與焦點有關嗎?
是電話號碼的輸入嗎? –