Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyListener not working on virtual keyboard

Tags:

I don't understand why this piece of code is not working. Only backspace and return key are detected. Listener doesn't fire for any other key. My device is Nexus One.

I tried to override activity's OnKeyDown method and that's even worse. The only detected button was hardware back button.

I am seeing around a suggestion to use TextWatcher and onTextChanged, while that might work in some cases, it's not a real work around. For example, if textbox is empty, you won't detect if user press BackSpace(Delete) button. So any ideas?

        TextView txtInput = (TextView)findViewById(R.id.txtInput);     txtInput.setOnKeyListener(new View.OnKeyListener() {         @Override         public boolean onKey(View v, int keyCode, KeyEvent event) {             makeToast(keyCode + " key pressed");             return true;         }     }); 
like image 230
bobetko Avatar asked Nov 26 '10 02:11

bobetko


2 Answers

Ok. I finally figured how to do what I want, and I am not proud on Android for this.

I am writing server/client application where on client I have to open SoftKeyboard and send pressed keys (characters and DEL key)... Each time key is pressed, that character is sent to server. If DEL is pressed I am sending sequence {BS} to server.

In order to do that I had to implement TextWatcher and onTextChange which works well except for situation when EditText is empty and user press DEL key. Since there is no change in EditText there is no way to detect that DEL key is pressed.

In addition to TextWatcher, I had to implement onKeyListener which I attached to my EditText control. This onKeyListener ignores all keys on SoftKeyboard except DEL and RETURN. Not sure why? A bug maybe?

Here is my code:

    TextView txtInput = (TextView)findViewById(R.id.txtInput);     txtInput.addTextChangedListener(inputTextWatcher);      txtInput.setOnKeyListener(new View.OnKeyListener() {         @Override         public boolean onKey(View v, int keyCode, KeyEvent event) {             Log.d(TAG, keyCode + " character(code) to send");             return false;         }     }); 

and TextWatcher....

private TextWatcher inputTextWatcher = new TextWatcher() {     public void afterTextChanged(Editable s) { }     public void beforeTextChanged(CharSequence s, int start, int count, int after)         { }     public void onTextChanged(CharSequence s, int start, int before, int count) {         Log.d(TAG, s.charAt(count-1) + " character to send");;               } }; 
like image 159
bobetko Avatar answered Oct 24 '22 23:10

bobetko


You have done one mistake here.
it should return true,If you handled the event. If you want to allow the event to be handled by the next receiver, return false
You are always returning true

like image 20
Labeeb Panampullan Avatar answered Oct 25 '22 00:10

Labeeb Panampullan