问题
I set TextWatcher
to EditText
like below. But when I try to clear text, cursor is coming to start after clearing every letter.
class MyInputWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
et.removeTextChangedListener(watcher2);
et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
et.addTextChangedListener(watcher2);
}
@Override
public void afterTextChanged(Editable s) {
}
}
回答1:
Please try like this
editText.setSelection(editText.getText().toString().length());
回答2:
Subhash Kumar, you can use method:
et.setSelection(position)
for displaying cursor in need position
回答3:
Set position to your cursor on afterTextChanged() method like this.
class MyInputWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
et.removeTextChangedListener(watcher2);
et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
et.addTextChangedListener(watcher2);
}
@Override
public void afterTextChanged(Editable s) {
et.setSelection(et.getText().toString().length())
}
}
回答4:
Every time you clear a character it calls onTextChanged()
method, as your implementation it get the edittext text and back set to it, so the cursor comes to the starting of the text. Clear et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
and it will be fixed. Or use this et.setSelection(et.getText().toString().length+1);
回答5:
Do it like this (UPDATED):
class MyInputWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String temp = s.toString().replaceAll("[^a-zA-Z]", "");
if (s.toString().length() != temp.length()) {
et.setText(temp);
et.setSelection(temp.length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
来源:https://stackoverflow.com/questions/41953259/edittext-cursor-coming-to-start-for-every-letter-when-clear-text