清除 EditText 中光标位置之前的单个字符

Gun*_*eep 5 android button cursor-position

使用下面的代码,我将替换包含子字符串的所有字符(如果我的编辑文本包含四个 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, ""));
Run Code Online (Sandbox Code Playgroud)

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

小智 5

我认为已经晚了但仍然如此。

您可以使用 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);
Run Code Online (Sandbox Code Playgroud)