Is there a way to override the behavior of WebView?

岁酱吖の 提交于 2019-12-21 05:18:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15097264/is-there-a-way-to-override-the-behavior-of-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!