我想控制editText的光标位置。我有一个与之相关的textwatcher。在editText中,文本是格式化的字符串。我想要的是在添加时我希望将光标保持在最后并且在删除时我想将光标保持在其删除的位置。我这样想。
我的问题是在添加文本时,它的光标位置不在文本的开头,而是在删除时虽然有时它可以将光标位置放在所需的位置,但它有时会使索引超出绑定异常。
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
formattedString = s.toString();
if (before > count) {
if (!formattedString.contains(",") && formattedString.length() > 4) {
StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.deleteCharAt(s.length() - 4);
formattedString = stringBuilder.toString();
}
} else {
EditText editText = editTextWeakReference.get();
editText.setSelection(0);
}
}
@Override
public void afterTextChanged(Editable editable) {
EditText editText = editTextWeakReference.get();
if (editText == null) {
return;
}
cursorPosition = editText.getSelectionEnd();
editText.removeTextChangedListener(this);
String cleanString = formattedString.toString().replaceAll("[¥,]", "");
if (cleanString.contains(".")) {
int dotPosition = cleanString.indexOf(".");
if (dotPosition == 6) {
cleanString = cleanString.substring(0, 6);
}
}
if (!cleanString.equals("")) {
if (!cleanString.contains(".")
&& cleanString.length() > 6) {
cleanString = cleanString.substring(0, cleanString.length() - 1);
}
}
String formatted = "";
if (!cleanString.equals("")) {
formatted = CurrencyUtil.getCurrency(cleanString);
}
editText.setText(formatted);
if (cursorPosition != 1) {
editText.setSelection(cursorPosition);
}
editText.addTextChangedListener(this);
}