Search code examples
androidandroid-edittextbackspace

Delete or backspace function. I created a button but cannot do a delete/backspace in my edittext


I want to delete the characters in my edittext one by one. I've research quite a bit but there are some problems, please advise. this is my sample code.

I created a delete button "ImageButton buttonDelete;"// XML imageButton1 and my edittext is "EditText display;"

display = (EditText) findViewById(R.id.editText1);
        buttonDelete.setOnClickListener(new View.OnClickListener()
        {
             public void onClick() 
             {
               // Get edit text characters
                String textInBox = display.getText():
                //Remove last character//
                String newText = textInBox.substring(0, textInBox.length()-1);
                // Update edit text
                display.setText(newText);

Solution

  • Try this:

    // Get edit text characters 
    String textInBox = display.getText().toString(); 
    if(textInBox.length() > 0)
    {
      //Remove last character// 
      String newText = textInBox.substring(0, textInBox.length()-1); 
      // Update edit text 
      display.setText(newText); 
    }