有没有一种方法可以覆盖WebView的行为? [英] Is there a way to override the behavior of WebView?
问题描述
我从布局中获得了WebView
:
WebView webView = (WebView) rootView.findViewById(R.id.myWebView);
我想覆盖onKeyDown
的行为.
通常,我可以通过子类覆盖它.
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....
}
}
但是,由于我是使用findViewById
来获取WebView的,因此有没有一种方法可以覆盖该方法?
However, since I got the WebView by using findViewById
, is there a way to override the method?
P.S:实际上,这是一个更为复杂的情况,我无法在MainActivity
中覆盖onKeyDown
,因为它首先在WebView
中调用onKeyDown
.
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.
推荐答案
如果要覆盖某些方法,则必须创建一个自定义的WebView
类,该类为extends WebView
.
If you want to override certain methods, you have to create a custom WebView
class which extends WebView
.
它看起来像这样:
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);
}
}
为此,您必须相应地更改XML布局文件:
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" />
另外,在给WebView
充气时,请确保将其转换为正确的类型,即CustomWebView
.
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);
否则,您将得到一个java.lang.ClassCastException
.
这篇关于有没有一种方法可以覆盖WebView的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!