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

EditText 實時字數統計與輸入上限控制

編輯:Android 程式設計入門

「還剩 12 字」這類提示在社交類 App 里幾乎是標配。實現起來不難,核心是给 EditText 挂一個 TextWatcher,在三個回調里分別記錄內容變化并更新計數。

布局與成員聲明

EditText content;    // 文本輸入框
TextView hasnumTV;   // 顯示剩余字數
int num = 140;       // 允許輸入的最大字數

content  = (EditText) findViewById(R.id.et_content);
hasnumTV = (TextView) findViewById(R.id.tv_num);
hasnumTV.setText(num + "");

核心:TextWatcher 監聽

content.addTextChangedListener(new TextWatcher() {

    private CharSequence temp;   // 變化前的內容快照
    private int selectionStart;
    private int selectionEnd;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // 變化即將發生,此時 s 還是舊內容
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        temp = s;   // 記錄最新內容
    }

    @Override
    public void afterTextChanged(Editable s) {
        // 實時刷新剩余字數
        int number = num - s.length();
        hasnumTV.setText("" + number);

        selectionStart = content.getSelectionStart();
        selectionEnd = content.getSelectionEnd();

        // 超長時刪掉多輸入的那一個字符
        if (temp.length() > num) {
            s.delete(selectionStart - 1, selectionEnd);
            content.setText(s);
            content.setSelection(temp.length());   // 光標定位到末尾
        }
    }
});

為什么要這么繞

afterTextChanged 里直接對 Editable 做刪除,會再次觸發 TextWatcher,稍不注意就是無限循環或光標亂跳。上面的寫法通過記錄 selectionStart / selectionEnd 并重新 setSelection,把光標位置穩住。

更省事的替代方案

如果只是限制字數,并不需要自定義提示 UI,直接在布局里加兩行即可:

<EditText
    android:id="@+id/et_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="140" />

如果需要更完整的體驗,還可以配合 TextInputLayout 的 setCounterEnabled(true) 與 setCounterMaxLength(140),計數器由控件自帶,無需自己寫 TextWatcher。

最后提醒:中英文、emoji 的字數計算口徑并不一致——emoji 在 Java 里占兩個 char。如果業務上要求「一個 emoji 算一個字」,應改用 s.codePointCount(0, s.length()) 來統計。

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