格式化(XXX) XXX-XXXX
格式的文本時,我的代碼工作正常。但是在刪除角色時,一旦到達角色-/()
就會停止。如果我再次將光標放到任何數字字符-/()
將自動被刪除。將自動添加字符移除到自定義PhoneNumberTextWatcher(XXX)XXX-XXXX的問題
這是我使用的代碼。
public class PhoneNumberTextWatcher implements TextWatcher {
private static final String TAG = PhoneNumberTextWatcher.class
.getSimpleName();
private EditText edTxt;
private boolean isDelete;
public PhoneNumberTextWatcher(EditText edTxtPhone) {
this.edTxt = edTxtPhone;
edTxt.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
isDelete = true;
}
return false;
}
});
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
if (isDelete) {
isDelete = false;
return;
}
String val = s.toString();
String a = "";
String b = "";
String c = "";
if (val != null && val.length() > 0) {
val = val.replace("-", "");
val = val.replace("(", "");
val = val.replace(" ", "");
val = val.replace(")", "");
if (val.length() >= 3) {
a = val.substring(0, 3);
} else if (val.length() < 3) {
a = val.substring(0, val.length());
}
if (val.length() >= 6) {
b = val.substring(3, 6);
c = val.substring(6, val.length());
} else if (val.length() > 3 && val.length() < 6) {
b = val.substring(3, val.length());
}
StringBuffer stringBuffer = new StringBuffer();
if (a != null && a.length() > 0) {
if (a.length() == 3) {
stringBuffer.append("("+a+")"+" ");
}
else{
stringBuffer.append(a);
}
}
if (b != null && b.length() > 0) {
stringBuffer.append(b);
if (b.length() == 3) {
stringBuffer.append("-");
}
}
if (c != null && c.length() > 0) {
stringBuffer.append(c);
}
edTxt.removeTextChangedListener(this);
edTxt.setText(stringBuffer.toString());
edTxt.setSelection(edTxt.getText().toString().length());
edTxt.addTextChangedListener(this);
} else {
edTxt.removeTextChangedListener(this);
edTxt.setText("");
edTxt.addTextChangedListener(this);
}
}
}
究竟你想幹什麼?刪除 - Char?或者它必須在第三位後 –
發生這種情況是因爲你的onKeyEvent永遠不會被調用,因此你必須手動處理刪除事件並相應地設置字符串的格式。您可以檢測刪除事件與我匹配的文本長度。例如在TextTextChanged之前將文本的長度保存在某個變量中,然後檢查afterTextChanged中輸入的文本的長度是否小於該長度。 –
格式化輸入的數字是完美的。我在刪除字符時遇到了問題,我添加了格式編號。意思是,雖然我刪除了最後4個數字,它不會刪除 - 當remove()時,同樣的問題。 –