Android - managing virtual and physical keyboard events

After reading the answers to several similar questions * I realized that onKeyListener () does not receive key events of keystrokes from the soft (virtual) keyboard. He only gets them from a hard (physical) keyboard. And a workaround would be to either use TextWatcher or onKeyboardActionListener. I have the following questions:

(1) Is there a way to listen for keystrokes from any keyboard (soft or hard) just using one listener? or basically one API that works for both?

(2) TextWatcher or onKeyboardActionListener, unlike the onKeyListener () onKey () method, do not skip the view that currently has focus (and in which the user enters input). So, how do I get the focal view now if I have to use TextWatcher or onKeyboardActionListener? I need this in order to be able to set some properties in an EditText in which the user enters his input based on the input.

* Related questions: onKeyListener does not work on the virtual keyboard , onKeyListener does not work with the soft keyboard (Android) , Android: why is my OnKeyListener () not called?

Thanks!

+4
source share
1 answer

I have the same problem. And suppose there is no good way to implement one solution to handle soft keyboard events. I implemented the onKeyListener() event for delete event and TextWatcher for key events.

 m_edtRecipients.addTextChangedListener(new TextWatcher() { boolean bConsumed = false; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!bConsumed) { RecipientsTextStyle.format(m_edtRecipients.getText(), m_dbProcessor); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (count != 0) { bConsumed = true; Log.d(TAG, "delete true"); } else { bConsumed = false; Log.d(TAG, "erase false"); } } @Override public void afterTextChanged(Editable s) { } }); 

There is one big drawback to the TextWatcher approach — you cannot change the editable associated with your EditText — this will cause a loop. Be careful!

+1
source

Source: https://habr.com/ru/post/1344858/


All Articles