Search code examples
javaandroidsubstringcursor-position

how to remove the last digit to the left of the cursor in EditText


I am was making a DEL button which would delete 1 char at a time. I recently added cursor movement to delete in between bud don't know how

I used substrings for deleting normally. It would crash if the number of chars was 0 or 1 before pressing it. I added if statement to fix it.

Here is my delete method

 public void delete(View view){
        if(textArea.length()==0){
            return;
        }else if(textArea.length()==1){
            if(textArea.getSelectionStart()==textArea.length()){
                textArea.setText("");
            }else{
                return;
            }

        }else {
            int selection = textArea.getSelectionStart();
            textArea.setText(textArea.getText().delete(Math.max(0, selection - 1), selection));
        }
    }

Please Tell How I could Do This To Delete the Char immediately left to the cursor.

I edited the code for the answerer


Solution

  • You can use delete method of Editable class like this

     public void delete(View view){
        int selection = textArea.getSelectionStart();
        textArea.setText(textArea.getText().delete(Math.max(0, selection - 1), selection));
    }