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.
If you want to override certain methods, you have to create a custom WebView class which extends WebView . 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.
Alternatives to WebView If you want to send users to a mobile site, build a progressive web app (PWA). If you want to display third-party web content, send an intent to installed web browsers. If you want to avoid leaving your app to open the browser, or if you want to customize the browser's UI, use Custom Tabs.
I did something similar: Just extend WebView and override onWindowVisibilityChanged . This way, the audio continues to play if the screen is locked or another app is opened. However, there will be no controls in the notification bar or on the lockscreen.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With