Enter key on EditText hitting onKey twice

2020-03-09 07:03发布

I've attached an OnKeyListener to an EditText. I've overrode the onKey handler to capture a KeyEvent.

When a user hits the enter key (either their computer enter key while using the emulator, or the hardware enter key on their phone with a hardware keyboard), the onKey handler gets executed twice. Both executions have the keyCode 66.

Why is this happening?

I want my screen so when the user hits the enter key, a search is performed. Because of what is happening, the search is needlessly happening twice.

My method looks like this:

   mFilter.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                // perform search
                return true;
            }
            return false;
        }
    });

标签: android
7条回答
Explosion°爆炸
2楼-- · 2020-03-09 07:58

I debugged and what worked for me was that,

editText.setOnKeyListener(View.OnKeyListener { view, i, keyEvent ->
            if (i == KeyEvent.KEYCODE_ENTER && enterAsSend && (keyEvent.action == KeyEvent.ACTION_UP || keyEvent.action == KeyEvent.ACTION_DOWN)) {
                //Do stuff
                }
                return@OnKeyListener true
            }
            false
        })

and checkout your Editext that android:inputType="textNoSuggestions" because the first click of enter key gives us the suggestion from the dictionary.

查看更多
登录 后发表回答