Atma
Atma

Reputation: 29775

how to add custom webview client to android activity

I have the following simple activity:

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

        wv.setWebChromeClient(new CustomWebViewClient());
}

I found the following code snippet for a custom webclient and want to use it in the above activity:

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;
        }
    }

I get the error:

Error:(53, 11) error: method setWebChromeClient in class WebView cannot be applied to given types; required: WebChromeClient found: MainActivity.CustomWebViewClient reason: actual argument MainActivity.CustomWebViewClient cannot be converted to WebChromeClient by method invocation conversion

What am I doing wrong?

Upvotes: 2

Views: 5954

Answers (2)

Gready
Gready

Reputation: 1164

WebViewClient

If you mean to use WebViewClient then simply replace WebViewClient with WebChromeClient and use a method that takes a WebViewClient object, i.e.,

wv.setWebViewClient(new CustomWebViewClient());

WebChromeClient

You'll need to extend WebChromeClient in your CustomWebViewClient.

setWebChromeClient() expects a WebChromeClient object as a parameter.

Change your class declerations:

private class CustomWebViewClient extends WebViewClient {

to

private class CustomWebViewClient extends WebChromeClient {

Upvotes: 0

nikis
nikis

Reputation: 11244

I believe you mixed up WebViewClient and WebChromeClient. If you are calling setWebChromeClient method, argument should be derived from WebChromeClient, not WebViewClient, for WebViewClient you should use setWebViewClient.

Upvotes: 1

Related Questions