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

时间:2013-02-26 19:07:53

标签: android android-webview

我从布局中获得了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,是否有办法覆盖该方法?

PS:这实际上是一个更复杂的案例,我无法覆盖onKeyDown中的MainActivity,因为它首先调用onKeyDown中的WebView。< / p>

1 个答案:

答案 0 :(得分:7)

如果要覆盖某些方法,则必须创建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