二進制輸入框輸入 `3` 導致解析異常,其他進制同理。
EditText edit = findViewById(R.id.edit);
edit.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = s.toString();
// 根據當前進制定義合法字符正則
String regex = currentBase == 2 ? "[01]*" :
currentBase == 8 ? "[0-7]*" :
currentBase == 10 ? "\\d*" : "[0-9A-Fa-f]*";
if (!input.matches(regex)) {
// 移除最後非法字符
edit.setText(input.substring(0, input.length()-1));
edit.setSelection(edit.length());
}
}
@Override public void afterTextChanged(Editable s) {}
});