限制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);
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容