Scroll webView with volume keys

2019-04-16 19:17发布

问题:

How do you scroll a webView w/ the volume hard keys? ...and can it be done with easing? If so, how? I'm a nooB to Android - Coming over from ActionScript and any help will be greatly appreciated.

my R.id.webPg001 is a WebView id.

This is where I'm at now:

@Override
  public boolean dispatchKeyEvent(KeyEvent event) {
      int action = event.getAction();
      int keyCode = event.getKeyCode();
      ScrollView scrollView;
      scrollView = (ScrollView) findViewById(R.id.webPg001);        
          switch (keyCode) {
          case KeyEvent.KEYCODE_VOLUME_UP:
              if (action == KeyEvent.ACTION_UP) {
                  scrollView.pageScroll(ScrollView.FOCUS_UP);
                  scrollView.computeScroll(); 
              }
              return true;
          case KeyEvent.KEYCODE_VOLUME_DOWN:
              if (action == KeyEvent.ACTION_UP) {
          scrollView.pageScroll(ScrollView.FOCUS_DOWN);
                  scrollView.computeScroll(); 
              }
              return true;
          default:
              return super.dispatchKeyEvent(event);
          }
      }

回答1:

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);
        }
    } 


回答2:

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).



回答3:

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.