Delete last character of edittext

android, android-edittext

Solution

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

Problem

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()?

Original source