我将TextWatcher
设置为EditText
,如下所示。但是当我尝试清除文本时,光标将在清除每个字母后开始。
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) {
}
}
答案 0 :(得分:0)
这样做(更新):
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) {
}
}
答案 1 :(得分:0)
Subhash Kumar,你可以使用方法:
et.setSelection(position)
用于在需要位置显示光标
答案 2 :(得分:0)
每次清除一个字符时,它都会调用onTextChanged()
方法,作为您的实现,它会获取edittext文本并将其设置为它,因此光标将显示在文本的开头。清除et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
,它将被修复。或者使用此et.setSelection(et.getText().toString().length+1);
答案 3 :(得分:0)
在像这样的afterTextChanged()方法上设置光标位置。
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 :(得分:0)
请尝试这样
editText.setSelection(editText.getText().toString().length());