Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 998
Robby Smet Avatar asked Sep 28 '12 08:09

Robby Smet


2 Answers

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));
    }
});
like image 96
erdo Avatar answered Sep 19 '22 05:09

erdo


try this out,

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


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

    yourEditText.setText ( str );
}
like image 37
Lucifer Avatar answered Sep 17 '22 05:09

Lucifer