I have a simple activity. Only one edittext and one button.After writing some text in the edittext if I press the button I want to delete the last character of the text.
I have tried like this:
String backSpace = txtMsg.getText().toString();
if(!backSpace.equals(""));
String mystring=backSpace.substring(0, txtMsg.length()-1));
txtMsg.setText("");
txtMsg.append(mystring);
It works fine but I want to manually append the backspace character at last position and finally at any position by moving the cursor(by txtMsg.setSelection());
Like we append any character to the end of the text:
txtMsg.append("C");
I want to know what will be in place of C for appending the backspace?Please Help
Thanks in advance.
I am not sure if you still need an answer to this or not, but I recently had the same need as you and I used the delete methond on the Editable android type:
http://developer.android.com/reference/android/text/Editable.html#delete(int,%20int)
I had a password EditText and did the following in the click handler for the 'delete' button:
// delete
if (m_userPass.getText().length() > 0) {
m_userPass.getText().delete(m_userPass.getText().length() - 1,
m_userPass.getText().length());
}
The delete method takes two arguments, the start and end position of the text to delete. In my example, I am just making the delete button delete the last character (regardless of the cursor). If you wanted to get fancier, you could put in logic to figure out the start and end position based on the cursor position.
The start position has to come before the end position (I accidentally made that mistake at first). And the start position has to be greater than or equal to zero.
there is a simple way of doing what you want via:
KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
input.dispatchKeyEvent(event);
You can try this, it worked for me:
if(!(text.length()==0))
text.setText(text.getText().delete(text.length() - 1, text.length()));