0

I have one backspace image button to delete one character after cursor inside an Editext field

<ImageButton
    android:id="@+id/backspace"/>

<EditText
    android:id="@+id/result"/>

And this is code

EditText resultEditText = (EditText)  getActivity().findViewById(R.id.result);

int curPostion;

curPostion = resultEditText.getSelectionEnd();

//getting the selected Text
SpannableStringBuilder selectedStr = new SpannableStringBuilder(resultEditText.getText());

//replacing the selected text with empty String
selectedStr.replace(curPostion - 1, curPostion, "");
resultEditText.setSelection(curPostion);

//Set new string
resultEditText.setText(selectedStr);

My problem is when I press the backspace button, one character is deleted successfully, but the cursor immediately come back to the first postion of the EditText.

How to remain cursor to the position after deleting a character?.

I'm really appreciate your help. Thank you very much.

Lucky Luke
  • 609
  • 1
  • 6
  • 18

1 Answers1

0

I just figured out the solution, just delcare a new variable to store the new cursor postion then setSelection().

In detail

EditText resultEditText = (EditText)  getActivity().findViewById(R.id.result);

int curPostion;

curPostion = resultEditText.getSelectionEnd();

//getting the selected Text
SpannableStringBuilder selectedStr = new SpannableStringBuilder(resultEditText.getText());

//replacing the selected text with empty String
selectedStr.replace(curPostion - 1, curPostion, "");

//Store postition
int afterDelPosition = curPostion - 1;

//Set new string resultEditText.setText(selectedStr);

//This will remain the cursor position
resultEditText.setSelection(afterDelPosition);

I hope this will be helpfull.

Lucky Luke
  • 609
  • 1
  • 6
  • 18