1. Download the #1 Android News App:   EarlyBird - News for Android
    Dismiss Notice

shouldOverrideKeyEvent doesn't work on webview

Last Updated:


    TERW_DAN New Member

    Code (Text):
    2. import android.app.Activity;
    3. import android.os.Bundle;
    4. import android.view.KeyEvent;
    5. import android.view.Window;
    6. import android.webkit.WebView;
    7. import android.widget.Toast;
    8. import android.webkit.WebViewClient;
    9. public class BWinBrowserActivity extends Activity {
    10. WebView webview;
    11.     /** Called when the activity is first created. */
    12.     @Override
    13.     public void onCreate(Bundle savedInstanceState) {
    15. requestWindowFeature(Window.FEATURE_NO_TITLE);
    16.         super.onCreate(savedInstanceState);
    17.         setContentView(R.layout.main);
    18.         webview = (WebView) findViewById(R.id.webview);
    19.         webview.getSettings().setJavaScriptEnabled(true);
    20.         webview.loadUrl("");  
    21.     }
    22. public boolean uiOverrideKeyEvent(KeyEvent event) {  
    23. if (webview != null) {  
    24. return webview.shouldOverrideKeyEvent(webview, event);  
    25. }  
    26. return false;  
    27. }
    28. }
    I have the following code. I'm trying to disable the complete default keyhandling by the webview component (the complete keyhandling is done by the loaded webpage in javascript).

    However, the shouldOverrideKeyEvent isn't working. Eclipse 3.5.2 return 'the method shouldOverrideKeyEvent is undefined for the type Webview'.
    However, if I check the Android documentation, it says shouldOverrideKeyEvent is a method of WebView.

    How to fix this?

  2. stevealbright

    stevealbright Developer Administrator

    I think what your looking to do is use the method shouldOverrideKeyEvent for a WebViewClient rather then what your currently doing with a WebView. A WebView does not contain the public method shouldOverrideKeyEvent.

    Hope that helps.


    TERW_DAN New Member

    When I use it on the webviewclient it seems to generate a bit less errors, but still it doesn't work (since there is no documentation on this, it is pretty hard to get it working).

    What I want to do is to catch every key, disable its default behaviour and send the keycode to a JS function, so I can handle the key in JS.

    Code (Text):
    2.     public boolean shouldOverrideKeyEvent(BWWebviewClient view, KeyEvent event){
    4. if ((KeyEvent = KeyEvent.KEYCODE_ENTER)){
    6. webview.loadUrl("javascript:getKeyCode(KeyEvent)");
    7. }
    9. return true;
    10.     }
    If I try to execute the code, it keeps nagging KeyEvent cannot be resolved in my if-statement. I have no clue why, since it can be found 1 rule above that, in the public boolean declaration.

    Can anyone help me on how to override a key, disable its default behaviour and then calling a JSfunction on my webpage, with the keyeevent?

Share This Page