Reputation: 260
I want to add text in textview in android, but when the backspace is pressed the last character should be removed.
This is my code:
@Override
public boolean dispatchKeyEvent(KeyEvent KEvent){
keyaction = KEvent.getAction();
if(keyaction == KeyEvent.ACTION_DOWN){
keycode = KEvent.getKeyCode();
keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() );
character = (char) keyunicode;
textView.setText(""+character);
}
return super.dispatchKeyEvent(KEvent);
}
Every time I press a key, textview is set with a new character and previous one gets overridden. Also if backspace is pressed than last character appended get deleted
Is there any way to do this to textview?
Upvotes: 2
Views: 3772
Reputation: 18677
You can use
textView.append("" + character);
Or
textView.setText(textView.getText().toString() + character);
This is the doc for TextView.append()
It seems it may cause an extra padding in your TextView() as described (and fixed) by this question.
You may want to check it also.
UPDATE
To detect backspace:
You may want to add some security checks (like string length and different null etc)
if(keyaction == KeyEvent.ACTION_DOWN){
if(keycode == KeyEvent.KEYCODE_DEL){
// Remove last char from string (like backspace would do)
textView.setText(textView.getText().toString().substring(0, textView.getText().length() - 1));
} else {
textView.append("" + character);
}
}
Upvotes: 7