Reputation: 552
I'm retrieving Accelerated Mobile Pages (APM) formatted HTML form a webcall. I'm then trying to display that AMP in a WebView. So I'm setting up my WebView like this:
webView = (WebView) findViewById(R.id.web_view);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
String content = article.getContentAmp();
webView.loadData(content, "text/html; charset=utf-8", null);
It displays content without error, but it's not displaying correctly. It ignores for example amp-youtube elements and embeded tweets.
Is there something else I have to do with the WebView or the WebChromeClient to display AMP correctly?
EDIT:
The answer below works. But in my specific case, I was using the WebView inside a NestedScrollView. Which worked fine in Android 5.0+, but below that, the amp- elements would not load.
Taking the WebView out of the NestedScrollView solved the problem. It's parent is now a relative layout.
So if you're having the same problem, try simplifying your layout so that the WebView is not deeply nested. And definitely don't put your WebView inside a NestedScrollView.
Upvotes: 2
Views: 1937
Reputation: 552
You cannot display elements such as embedded youtube videos, images, tweets etc without giving the WebView a base url. The solution was to use webview.loadDataWithBaseUrl instead on webView.loadData. You must pass it a valid url.
webView = (WebView) findViewById(R.id.web_view);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
String content = article.getContentAmp();
String baseUrl = extractUrlFromContent(content);
webView.loadDataWithBaseURL(baseUrl, content, "text/html", "utf-8", "");
Upvotes: 1