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