2

I want to add text in textview in android, but when the backspace is pressed the last character should be removed.

  • I am using softkeyboard.
  • I am creating textview dynamically.
  • and update textview when key of soft-keyboard is dispatched/pressed.

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?

saksham agarwal
  • 250
  • 3
  • 14

1 Answers1

7

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);
    }
}
Community
  • 1
  • 1
guipivoto
  • 18,327
  • 9
  • 60
  • 75