限制EditText輸入行數

網上看了很多資源,發現不符合要求,在中間插入字符,光標都會移動到最后,自己修改了部分代碼,暫時沒發現問題,貼出來記錄下。

private TextWatcher watcher = new TextWatcher() {
    String tmp;
    int cursor;

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

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int line = editText.getLineCount();
        if (line > MAX_LINE) {
            if (before > 0 && start == 0) {
                if (s.toString().equals(tmp)) { 
                     // setText觸發遞歸TextWatcher
                    cursor--;
                } else { 
                    // 手動移動光標為0
                    cursor = count - 1;
                }
            } else {
                cursor = start + count - 1;
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        // 限制可輸入行數
        int line = editText.getLineCount();
        if (line > MAX_LINE){
            String str = s.toString();
            tmp = str.substring(0, cursor) + str.substring(cursor + 1);
            editText.setText(tmp);
            editText.setSelection(cursor);
        }
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容