Clearing the single character before cursor position in EditText

4.1k Views Asked by At

With the below code i am replacing the all characters(if my edittext contains four a's all a's are removed here) that contains substring and the cursor position is goes to before first character in edittext field.

//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, ""));

How can i clear the single character before the cursor position(if my cursor is middle of the edittext) without changing the cursor position.

3

There are 3 best solutions below

0
On

I solved with this function:

int pos = editText.getSelectionStart();
if (pos > 0)
    String text = editText.getText().delete(pos - 1, pos).toString();
1
On

I think its late but still.

You can use 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);
0
On

Perfect solution try this... Wherever you will put your cursor the value will gets remove from that position

  Editable editable = yourEditText.getText();
    int charCount = mDigits.getSelectionEnd();
    if (charCount > 0) {
    editable.delete(charCount - 1, charCount);
    }