在Android WebView中读取键盘事件
作者:互联网
我正在尝试在android web视图中收听关键事件.用户填写表单时的示例,我应该收到关键事件.这是我的WebView代码
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;
}
.....
}
当用户键入文本框或textareas时,都不会调用onKeyDown,onKeyUp和onKey方法.是否有可能实现这一点,或者Android是否限制了这种可能的隐私泄露?
解决方法:
警告!此解决方案仅支持英文字母.
完成后无需访问HTML源代码或JS事件.适用于Android 5.0.2的软键盘和硬键盘.
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/issues/detail?id=42904#c15
标签:keyevent,android,webview,android-webview,android-softkeyboard 来源: https://codeday.me/bug/20190930/1836788.html