我有一个应用程序,它从数据库中获取数据,然后将其显示为文章列表。数据被获取并放入带有 WebView 的 recyclerView 中。
一篇特定的文章有这个 html:
<div style="position: absolute; height: 100%; background: url('https://www.softray.it/wp-content/uploads/2015/10/home-test-6.2.png') no-repeat;">
<div style="height: 100%; width: 50%; margin-left: auto; margin-right: auto;display: table-cell; vertical-align: middle; text-align: center;">
<h1 style="padding: 10px; text-align: center; font-family: 'Open Sans', sans-serif; color: #ffffff;">SOFTRAY TECHNOLOGY</h1>
<p style="padding-left: 5px; text-align: center; color: #ffffff; font-family: 'Open Sans', sans-serif;">La potenza del mobile re-inventa le applicazioni business e un nuovo stile di IT</p>
</div>
</div>
*对于乱七八糟的 html 很抱歉,我只是在数据库上没有像样的编辑工具。
这里的问题是我的背景图片没有显示,甚至第二个 div
也没有按应有的方式垂直居中。
我尝试在显示数据之前将 html
和 body
标记附加到我的数据,但仍然没有加载背景图像。
holder.webView.loadData("<html style='height:100%;'><body style='height:100%;margin:0;padding:0;'>" + s + "</body></html>", "text/html", "utf-8");
我知道我可能必须给元素一个固定的高度,但我想适应任何屏幕。有什么建议吗?
编辑:我只需要获取 webview 内容的高度(以像素为单位),这样我就可以在 html
标记中进行设置。
问题是我需要在加载数据之前知道这个维度。
最佳答案
尝试将 html 代码保存为 assets 文件夹中的 example.html 文件,然后使用以下方式加载 Web View :
webView.loadUrl("file:///android_asset/example.html");
Web View 应使用 match_parent 作为宽度和高度以覆盖其父布局的 100%。
编辑:
从服务器获取数据时,可以实现这个方法:
private void saveHtmlFile(String htmlStr) {
String path = "/data/data/" + getApplicationContext().getPackageName() + "/files/";
String fileName = "example";
fileName = fileName + ".html";
File file = new File(path, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
byte[] data = htmlStr.getBytes();
out.write(data);
out.close();
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///data/data/" + getApplicationContext().getPackageName() + "/files/example.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
请检查此链接一次:
关于高度为 :100% and a background image 的 Android webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51396738/