简体   繁体   中英

Android - handle virtual & physical keyboard events

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

(1) Is there a way to be able to listen to key presses from any keyboard (soft or hard) by just implementing one listener? or basically a single API that works for both?

(2) TextWatcher or onKeyboardActionListener, unlike onKeyListener()'s onKey() method, do not pass the view that currently has focus (and in which the user is typing input). So, how do I get the currently focussed view if I were to use TextWatcher or onKeyboardActionListener? I need this to be able to set some properties on the EditText in which the user is keying their input, based on the input.

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

Thanks!

I've got the same problem. And suppose, that there is no good way to implement one solution for handling soft keyboard events. I've implemented onKeyListener() for delete event and TextWatcher for keys event.

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 disadvantage with TextWatcher approach - you cannot change editable that your EditText is linked - it will cause the loop. Be careful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM