Delete last edittext character

I have a quick question.

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

input.append(number);

I also have a tray, when the user clicks on this button, I want to delete 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? Is there something in the input.remove () line?

+5
source share
2 answers

I understand this is an old question, but it is still valid. If you crop the text yourself, the cursor will reset to the beginning when you set Text (). So, instead (as njzk2 mentioned), send a fake key removal 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));
    }
});
+10
source

try it,

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


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

    yourEditText.setText ( str );
}
+8
source

All Articles