Scroll webView with volume keys

为君一笑 提交于 2019-12-04 21:08:38

Here is the correct code: (thnx NdrU!!)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    WebView scrollView = (WebView) findViewById(R.id.ch01);     
        switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_DOWN) {
                scrollView.pageUp(false);   
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                scrollView.pageDown(false);
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
        }
    } 

WebView has methods pageUp and pageDown, according to the javadoc, they scroll half a page, so you will probably want to call them twice to get a full page scroll.

As to the code you have, I thought the preffered way to listen to button presses is by overriding onKeyUp and onKeyDown methods, but I might be wrong (I'm new to android development myself).

Just in case you're not aware, the normal mechanism for navigation is to use the arrow keys or trackball for hardware-level navigation. Your webviews should plug in to this mechanism with no additional effort on your part, and so unless you have a clear application-specific reason for tapping into the volume keys, I would recommend using the built-in functionality here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!