1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > android edittext限制输入行数 限制EditText输入行数

android edittext限制输入行数 限制EditText输入行数

时间:2019-04-23 12:53:27

相关推荐

android edittext限制输入行数 限制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);

}

}

};

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。