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 . Usually 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 a WebView using findViewById , is there a way to override the method?

PS: This is actually a much more complicated case, and I cannot override onKeyDown in MainActivity , because it first calls onKeyDown in the WebView .

+4
source share
1 answer

If you want to override some methods, you need to create your own WebView class, which extends WebView .

It will 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 must modify your XML layout file accordingly:

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

In addition, when you pump up the WebView , make sure you throw it on the correct type, which is equal to CustomWebView .

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

Otherwise, you will get java.lang.ClassCastException .

+6
source

All Articles