问题描述
我正在尝试在 android web 视图中监听关键事件.例如,当用户填写表单时,我应该收到关键事件.这是我的 WebView 代码
I'm trying to listen to key events in android web view. Example when user is filling a form, I should receive the key events. This is my WebView code
public class MyWebView extends WebView implements OnKeyListener
{
.....
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
Log.i("PcWebView", "onKeyDown keyCode=" + keyCode);
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
Log.i("PcWebView", "onKeyUp keyCode=" + keyCode);
return super.onKeyUp(keyCode, event);
}
@Override // Listener is initialized in the constructor
public boolean onKey(View v, int keyCode, KeyEvent event)
{
Log.i("PcWebView", "onKey keyCode=" + keyCode);
return false;
}
.....
}
当用户输入文本框或文本区域时,onKeyDown
、onKeyUp
和 onKey
方法都不会被调用.是否有可能实现这一点,或者 Android 是否限制了可能侵犯隐私的原因?
neither of the methods onKeyDown
, onKeyUp
and onKey
are being called when user types into the textboxes or textareas. Is it possible to achieve this or has Android restricted this b'cos of a possible privacy breach?
推荐答案
注意!此解决方案仅支持英文字母.
无需访问 HTML 源代码或 JS 事件即可完成.适用于我的 Android 5.0.2 软键盘和硬件键盘.
Accomplished without any access to the HTML source code or JS events. Works for me on Android 5.0.2 for both soft and hardware keyboards.
public class MyWebView extends WebView {
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new BaseInputConnection(this, false); //this is needed for #dispatchKeyEvent() to be notified.
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean dispatchFirst = super.dispatchKeyEvent(event);
// Listening here for whatever key events you need
if (event.getAction() == KeyEvent.ACTION_UP)
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_SPACE:
case KeyEvent.KEYCODE_ENTER:
// e.g. get space and enter events here
break;
}
return dispatchFirst;
}
}
这里的技巧是用一个简化的实现来覆盖系统提供的 InputConnection
输入实现.默认情况下,阻止开发人员访问这些事件是 Google 员工有意设计的.因为关键事件输入不再是唯一的了.有手势、声音等等.官方建议是完全停止依赖传统的关键事件进行文本输入".在此处查看更多详细信息:https://code.google.com/p/android/问题/细节?id=42904#c15
The trick here is overriding the system-provided input implementation of InputConnection
with a simplified one. Preventing developers from accessing the events by default was made by Googlers on purpose. Because the key event input isn't the only one anymore. There're gestures, voice and more is coming. Official recommendation is to "stop relying on legacy key events for text entry at all". Check out more details here: https://code.google.com/p/android/issues/detail?id=42904#c15
这篇关于在 Android WebView 中读取键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!