对 Android 按键事件处理感到困惑。有什么好的解释吗?
我是 Android 的新手。对于如何在 EditText/TextView 中监听按键和软键,有人有一个理智的解释吗?
我很想看到一个全面的教程或一组示例。
据我了解,我可以向我的 Activity 添加一个 KeyListener,例如 onKeyDown()、onKeyUp(),但是当我尝试这样做时,我无法触发仅 HOME 和 BACK 等普通键的事件。
我见过提到使用 TextWatcher,但这与处理原始按键事件不同。
SO 上似乎有很多半解决方案。希望能帮您解开迷雾……
I'm a relative beginner with Android. Does anybody have a sane explanation for how to listen for keys and soft keys in an EditText/TextView?
I'd love to see a comprehensive tutorial or set of examples.
As I understand it, I can add a KeyListener to my Activity, e.g. onKeyDown(), onKeyUp() but when I try this I can't trigger the events for normal keys only HOME and BACK for example.
I have seen mention of using a TextWatcher but that isn't the same as handling raw key events.
There seem to be a number of half-solutions here on SO. Hoping you can help clear the mists of confusion...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须将一个关键侦听器分配给 EditText 本身,而不是 Activity。
You have to assign a key listener not to activity but rather to EditText itself.
这就是我必须监听 BACK 或 MENU 键事件。只需添加此方法,无需实现任何接口。我在我的 BaseActivity 中执行此操作,每个 Activity 都从中继承。
PS:我强烈建议不要忽略后退键。
This is what I have to listen to BACK or MENU key events. Simply add this method, without implementing any Interface. I do this in my BaseActivity, from which every Activity inherits.
PS: I highly discourage ignoring the back key.
例如:
For example:
我最近发现了另一种方法,即使用 Activity
onKeyDown
或使用view.setOnKeyListener< 在视图上设置关键侦听器的事件(在我的情况下,这并不能真正处理来自 ADB 的关键事件)。 /代码>。
由于 android
P
方法addOnUnhandledKeyEventListener
已经被引入。当您的视图能够捕获未处理的关键事件时,它允许您做任何您需要做的事情。这是我如何使用它的示例:
I recently found another way that be stuck using Activity
onKeyDown
, or event setting a key listener on view (which is not really working with key events from ADB in my case) withview.setOnKeyListener
.Since android
P
methodaddOnUnhandledKeyEventListener
has been introduced. It allows you to do whatever you need to do when your view is able to catch unhandled key events.Here is an example of how I used it :