android WebView:在JavaScript中处理箭头键

时间:2012-04-16 10:59:43

标签: javascript android javascript-events android-webview

我有一个简单的WebView应用程序,我想用键盘控制它。 是否可以在javascript中捕获箭头键?

我试过以下代码没有任何运气:

function handleArrowKeys(evt) {
    console.info('key');                                                                                         
}

document.onkeyup = handleArrowKeys;
document.onkedown = handleArrowKeys;
document.onkepress = handleArrowKeys;

在webview中启用了javascript

WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);

1 个答案:

答案 0 :(得分:4)

您应该覆盖WebView的onKeyDown方法。 请参阅:http://blog.csdn.net/focusxi/article/details/6780965

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event){
    int valKey = 0;
    System.out.println("Web KEY:"); 
    System.out.println(keyCode);    

    switch(keyCode){
        //UP
        case 50:
        case 19:
            valKey = 19;
            break;
        //DOWN
        case 83:
        case 20:
            valKey = 20;        
            break;
        //LEFT
        case 81:
        case 21:
            valKey = 21;
            break;
        //RIGHT
        case 69:
        case 22:
            valKey = 22;    
            break;
    }

    if (valKey!=0)
    {
        //new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT);
        KeyEvent event1 = new KeyEvent(KeyEvent.ACTION_DOWN, valKey);

        System.out.println(event1.getKeyCode());    

        return super.onKeyDown(38, event1);
    }
    else
    {
        return super.onKeyDown(keyCode, event);
    }

}
}