jason
jason

Reputation: 35

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);

Upvotes: 1

Views: 2820

Answers (2)

Mark
Mark

Reputation: 1

BtonBackSpace.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String bs = null;
            if(Tfield.getText().length()>0){
                StringBuilder Strb = new StringBuilder(Tfield.getText());
                Strb.deleteCharAt(Tfield.getText().length() - 1);
                bs = Strb.toString();
                Tfield1.setText(bs );

            }

Upvotes: 0

Yaqub Ahmad
Yaqub Ahmad

Reputation: 27659

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); 
}

Upvotes: 3

Related Questions