Dragon warrior Dragon warrior - 2 months ago 9
Android Question

Is there a way to override the behavior of WebView?

I get the

WebView
from my layout:

WebView webView = (WebView) rootView.findViewById(R.id.myWebView);


I want to override the behavior of
onKeyDown
.
Normally, I can override it by subclassing.

WebView webView = new WebView(this) {

@Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
// Do my stuff....
}
}


However, since I got the WebView by using
findViewById
, is there a way to override the method?

P.S: It is actually a much more complicated case, and I can't Override
onKeyDown
in
MainActivity
, because it call the
onKeyDown
in
WebView
first.

Answer

If you want to override certain methods, you have to create a custom WebView class which extends WebView.

It would look something like this:

public class CustomWebView extends WebView {

    public CustomWebView(Context context) {
        this(context, null);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        /* any initialisation work here */
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /* your code here */
        return super.onKeyDown(keyCode, event);
    }

}

For this to work, you have to change your XML layout file accordingly:

<com.example.stackoverflow.CustomWebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Also, when you are inflating the WebView, make sure you are casting it to the correct type which is CustomWebView.

CustomWebView webView = (CustomWebView) findViewById(R.id.webview);

Otherwise, you will get a java.lang.ClassCastException.