I'm attempting to make a way for a user to input text into a TextView from an EditText. However, if the user enters something, and wants to fix it, I want them to be able to press space on an empty EditText to get the last thing they wrote back. The first problem is, if they type in "hello", hit enter to add it to the TextView (which clears it from the EditText), then hit space, the EditText then has " hello". Not what I want, and I can't figure out why.
My code to place the entered text into a holding string:
b1 = ti.getText().toString();
Then, if the user hits the space key, I believe they should get b1 in the EditText. Instead, I get: " " + b1
. Why is this added space in there?
if((event.getAction()==KeyEvent.ACTION_DOWN)&&(key == KeyEvent.KEYCODE_SPACE)){
if(ti.getText().toString().equals("")){
ti.setText(b1);
}
My second, bigger problem is that the above code only works on a hardware keyboard. What is the key event for a software keyboard pressing space?
This is all in an onKeyListener.
For your first problem I suspect you need to return true from your onKey method in the onKeyListener when your 'if' condition is met, to indicate that the event is consumed, otherwise you get the default onKeyListener adding the space to the EditText. i.e.:
This extract from the KeyEvent API docs should help with problem 2: "As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged. You should never rely on receiving KeyEvents for any key on a soft input method. In particular, the default software keyboard will never send any key event to any application targetting Jelly Bean or later, and will only send events for some presses of the delete and return keys to applications targetting Ice Cream Sandwich or earlier. Be aware that other software input methods may never send key events regardless of the version. Consider using editor actions like IME_ACTION_DONE if you need specific interaction with the software keyboard, as it gives more visibility to the user as to how your application will react to key presses."
An easy way to solve the extra space problem is to just remove the space from the String before you put it into the EditText
p.s. I strongly recommend more descriptive variable names. Your programs are likely to be confusing to work on if you use names like ti and b1. Perhaps these choices make more sense in the context of your program. But from what you've shown here it is not easy to tell what these names refer to.