【问题标题】:how to add custom webview client to android activity如何将自定义 webview 客户端添加到 android 活动
【发布时间】:2015-04-21 20:44:46
【问题描述】:

我有以下简单的活动:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webview);

        wv.setWebChromeClient(new CustomWebViewClient());
}

我为自定义 web 客户端找到了以下代码 sn-p,并希望在上述活动中使用它:

private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.contains("mysite.com")) {
                view.loadUrl(url);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            return true;
        }
    }

我得到错误:

错误:(53, 11) 错误: 类 WebView 中的方法 setWebChromeClient 不能应用于给定类型;必需:WebChromeClient 找到: MainActivity.CustomWebViewClient 原因:实际参数 MainActivity.CustomWebViewClient 无法转换为 WebChromeClient 按方法调用转换

我做错了什么?

【问题讨论】:

    标签: java android webview inner-classes


    【解决方案1】:

    我相信你混淆了WebViewClientWebChromeClient。如果你调用setWebChromeClient方法,参数应该从WebChromeClient派生,而不是WebViewClient,对于WebViewClient你应该使用setWebViewClient

    【讨论】:

      【解决方案2】:

      WebViewClient

      如果您打算使用WebViewClient,那么只需将WebViewClient 替换为WebChromeClient 并使用采用WebViewClient 对象的方法,即,

      wv.setWebViewClient(new CustomWebViewClient());
      

      WebChromeClient

      您需要在您的CustomWebViewClient 中扩展WebChromeClient

      setWebChromeClient() 需要 WebChromeClient 对象作为参数。

      更改你的类声明:

      private class CustomWebViewClient extends WebViewClient {
      

      private class CustomWebViewClient extends WebChromeClient {
      

      【讨论】:

        猜你喜欢
        • 2012-03-07
        • 2022-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        相关资源
        最近更新 更多