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()?
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));
}
});
try this out,
String str = yourEditText.getText().toString().trim();
if(str.length()!=0){
str = str.substring( 0, str.length() - 1 );
yourEditText.setText ( str );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With