gpt4 book ai didi

android - 有没有办法覆盖 WebView 的行为?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:23 24 4
gpt4 key购买 nike

我从我的布局中获取了 WebView:

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

我想覆盖 onKeyDown 的行为。通常,我可以通过子类化来覆盖它。

        WebView webView = new WebView(this) {

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

但是,由于我是通过findViewById获取WebView的,有没有办法重写该方法?

P.S: 这实际上是一个更复杂的情况,我不能在 MainActivity 中覆盖 onKeyDown,因为它调用了 onKeyDown首先在 WebView 中。

最佳答案

如果你想覆盖某些方法,你必须创建一个自定义 WebView 类,它 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 布局文件:

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

此外,当您为 WebView 充气时,请确保将其转换为正确的类型,即 CustomWebView

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

否则,您将得到一个 java.lang.ClassCastException

关于android - 有没有办法覆盖 WebView 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15097264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com