开发者

Android - handle virtual & physical keyboard events

开发者 https://www.devze.com 2023-02-19 06:17 出处:网络
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.

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 开发者_JAVA技巧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!

0

精彩评论

暂无评论...
验证码 换一张
取 消