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

Android EditText 字數限制實作:以位元組而非字元計算

編輯:關於 Android 程式設計

表單類需求常會限制輸入長度。若直接用 android:maxLength,Android 是以「字元數」計算的,一個中文字和一個英文字母都算 1,這在很多後端仍以 byte 計算的場景下並不合用。以下示範用 TextWatcher 自己攔截,並以 GBK 位元組數作為限制依據。

實作思路

  1. 實作 TextWatcher,在 onTextChanged 中快取目前的 CharSequence。
  2. 在 afterTextChanged 中把文字轉成 byte 陣列,取得實際位元組長度。
  3. 若超過上限,刪掉最後一個輸入字元、重新 setText,並把游標移回正確位置。
  4. 同時跳出提示訊息告知使用者。

程式碼

public class EditTextWatcher implements TextWatcher {

    private static final String TAG = "EditTextWatcher";
    private CharSequence temp;
    private int selectionStart, selectionEnd;

    private int range = 3;          // 字數(位元組)上限
    private String infoString;      // 提示訊息
    private Activity mActivity;
    private EditText mEditText;

    public EditTextWatcher(Activity activity, EditText text) {
        this.mActivity = activity;
        this.mEditText = text;
    }

    public void setInfomation(String infoString, int range) {
        this.range = range;
        this.infoString = infoString;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        temp = s;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void afterTextChanged(Editable s) {
        int textLength = 0;
        try {
            // 必須指定編碼,否則不同平台結果會不一致
            textLength = temp.toString().getBytes("gbk").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (textLength > range) {
            selectionStart = mEditText.getSelectionStart();
            selectionEnd = mEditText.getSelectionEnd();

            ToastUtils.show(mActivity, infoString);

            s.delete(selectionStart - 1, selectionEnd);
            int tempSelection = selectionStart - 1;
            mEditText.setText(s);
            mEditText.setSelection(tempSelection);
        }
    }
}

使用方式

EditTextWatcher watcher = new EditTextWatcher(this, etContent);
watcher.setInfomation("最多只能輸入 100 個位元組", 100);
etContent.addTextChangedListener(watcher);

幾個實務提醒

  • 位元組長度與字元長度不同:GBK 下一個中文字佔 2 bytes,UTF-8 則佔 3 bytes。要先確認後端或資料庫欄位用的是哪種編碼,再決定 getBytes 的參數。
  • afterTextChanged 中直接呼叫 setText 會再次觸發 TextWatcher,實作時要留意避免無限遞迴;實務上可改用 s.replace() 或直接操作 Editable,並搭配一個 boolean 旗標做重入保護。
  • 游標位置需自行校正,否則中文輸入法候選字組合時容易出現游標跳動或文字錯位。
  • 若只是限制「字元數」而非位元組,直接用 EditText 的 maxLength 屬性即可,不必自幹。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved