Robby Smet
Robby Smet

Reputation: 4661

Delete last character of edittext

I have a quick question.

I have a screen with some numbers, when you click one of the numbers, the number gets appended to the end of the edittext.

input.append(number);

I also have a backbutton, when the user clicks this button I want to remove the last character.

At the moment I have the following :

Editable currentText = input.getText();

if (currentText.length() > 0) {
    currentText.delete(currentText.length() - 1,
            currentText.length());
    input.setText(currentText);
}

Is there an easier way to do this ? Something in the line of input.remove()?

Upvotes: 6

Views: 14362

Answers (2)

erdo
erdo

Reputation: 136

I realise this is an old question but it's still valid. If you trim the text yourself, the cursor will be reset to the start when you setText(). So instead (as mentioned by njzk2), send a fake delete key event and let the platform handle it for you...

//get a reference to both your backButton and editText field

EditText editText = (EditText) layout.findViewById(R.id.text);
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button);

//then get a BaseInputConnection associated with the editText field

BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true);

//then in the onClick listener for the backButton, send the fake delete key

backButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
    }
});

Upvotes: 12

Lucifer
Lucifer

Reputation: 29662

try this out,

String str = yourEditText.getText().toString().trim();


   if(str.length()!=0){
    str  = str.substring( 0, str.length() - 1 ); 

    yourEditText.setText ( str );
}

Upvotes: 9

Related Questions