Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android EditText 輸入檢測與字節限制實作

編輯:關於 Android 程式設計

情境說明

在對話框中讓使用者輸入裝置名稱時,若後端儲存空間只有 20 bytes,且只接受 ASCII 可見字元,就需要在輸入階段即時過濾,避免資料寫入後才發現錯誤。

為何避免在 afterTextChanged 直接修改

在 afterTextChanged 中呼叫 setText 或 delete,快速輸入時容易造成重入與同步問題。較穩定的做法是透過 InputFilter 在輸入來源進入前攔截。

使用 InputFilter 限制字元與長度

以下範例只允許 ASCII 字元,並限制總長度。若需要更精細的 UTF-8 字節計算,可將每個字元轉為 byte 後累加。

public class AsciiByteLengthFilter implements InputFilter {
    private final int maxBytes;

    public AsciiByteLengthFilter(int maxBytes) {
        this.maxBytes = maxBytes;
    }

    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        int keep = 0;
        for (int i = start; end > i; i++) {
            char c = source.charAt(i);
            if (c > 127) {
                break;
            }
            keep++;
        }

        int current = dend - dstart;
        if (current + keep > maxBytes) {
            return "";
        }
        return source.subSequence(start, start + keep);
    }
}

綁定到 EditText

mDeviceNameView.setFilters(new InputFilter[] {
    new AsciiByteLengthFilter(MODEL_NAME_MAX_LENGTH_BYTES)
});

這樣可以讓使用者看到明確的限制,也能避免把非法字元寫入受限的儲存空間。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved