4

使用下面的代码,我将替换包含子字符串的所有字符(如果我的编辑文本包含四个 a,则此处删除所有 a),并且光标位置位于编辑文本字段中的第一个字符之前。

//getting cursor position 
int end = t1.getSelectionEnd();
//getting the selected Text
String selectedStr = t1.getText().toString().substring(end-1, end);
//replacing the selected text with empty String and setting it to EditText
t1.setText(t1.getText().toString().replace(selectedStr, ""));

如何在不更改光标位置的情况下清除光标位置之前的单个字符(如果我的光标位于编辑文本的中间)。

4

3 回答 3

4

我认为它迟到了,但仍然。

您可以使用 SpannableStringBuilder。

//getting cursor position 
int end = t1.getSelectionEnd();
//getting the selected Text
SpannableStringBuilder selectedStr=new SpannableStringBuilder(t1.getText());
//replacing the selected text with empty String and setting it to EditText
selectedStr.replace(end-1, end, "");
edittext1.setText(selectedStr);
于 2014-10-20T11:43:54.263 回答
1

我用这个功能解决了:

int pos = editText.getSelectionStart();
if (pos > 0)
    String text = editText.getText().delete(pos - 1, pos).toString();
于 2017-07-16T14:32:34.190 回答
0

完美的解决方案试试这个......无论你将光标放在哪里,值都会从那个位置删除

  Editable editable = yourEditText.getText();
    int charCount = mDigits.getSelectionEnd();
    if (charCount > 0) {
    editable.delete(charCount - 1, charCount);
    }
于 2017-08-10T13:30:42.390 回答