Android:将 AMP 格式 HTML 加载到 WebView

Android: Loading AMP Formatted HTML into a WebView

我正在通过网络电话检索格式为 HTML 的加速移动页面 (APM)。然后我尝试在 WebView 中显示该 AMP。所以我正在这样设置我的 WebView:

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

显示内容没有错误,但显示不正确。它会忽略例如 amp-youtube 元素和嵌入的推文。

我还需要对 WebView 或 WebChromeClient 做些什么才能正确显示 AMP 吗?

编辑:

下面的答案有效。但在我的具体情况下,我在 NestedScrollView 中使用 WebView。在 Android 5.0+ 中运行良好,但低于该版本时,amp- 元素将无法加载。

从 NestedScrollView 中取出 WebView 解决了这个问题。它的父级现在是相对布局。

因此,如果您遇到同样的问题,请尝试简化您的布局,以便 WebView 不会嵌套得很深。绝对不要将 WebView 放在 NestedScrollView 中。

如果不为 WebView 提供基础 url,则无法显示嵌入的 youtube 视频、图像、推文等元素。解决方案是使用 webview.loadDataWithBaseUrl 而不是 webView.loadData。您必须传递一个有效的 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", "");