首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android Java 進制轉換越界:TextWatcher 實時攔截非法輸入

     編輯:程式設計疑難解答

問題

二進制輸入框輸入 `3` 導致解析異常,其他進制同理。

解決:TextWatcher 過濾輸入


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) {}
});

進階

  • 使用 `InputFilter` 直接過濾:`edit.setFilters(new InputFilter[]{ (source, start, end, dest, dstart, dend) -> source.toString().matches(regex) ? null : "" });`
  • 解析時 `Integer.parseInt(str, base)` 捕獲 `NumberFormatException` 兜底。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved