【发布时间】:2019-10-04 18:21:33
【问题描述】:
我正在尝试在 WebView 中呈现带有本地图像的本地 html 文件,其中 WebView 在对话框中而不是 Activity 中。图像没有被渲染,但信息的其余部分显示得很好。
Stack Overflow 中建议了无数解决此问题的方法,其中许多带有绿色复选标记。我试过的都没有用。
我正在做的是将 html 文件和图像放在 res/raw 中 html 文件有一行引用图像;我尝试了不同的选项,所有这些选项都在堆栈溢出的某处被声明为有效,例如:
<img src="file:///android_res/raw/main_screen_crop.png" alt="Main Screen" width="525" height="290">
和
<img src="main_screen_crop.png" alt="Main Screen" width="525" height="290">
html 的文本部分渲染得很好,但对于图像,我只得到一个带有缩略图图标的空框内的“alt”文本。
所以我的问题是:
- 当 WebView 的 html 在不同于 Activity 的 Dialog Box 中呈现时访问图像是否会导致建议的解决方案无效?
- 一些答案说“将图像放在资产目录中并使用 file:///...”来引用图像,他们表示这是必需的,这与其他的相矛盾 解决方案。是否需要使用资产目录?
- Android 有一个 2018 年的教程 https://www.youtube.com/watch?v=HGZYtDZhOEQ 指出 StackOverflow 上关于如何处理 WebView 的许多答案都是完全错误的,但承认由于文档过时,部分原因是他们的错...
这是我的渲染代码,它适用于其他一切!
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
@SuppressLint("InflateParams") // Okay on dialog
final View helpContent = inflater.inflate(R.layout.help_screen, null);
// Get the Alert Dialog Builder
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
TextView customTitle = new TextView(context);
// Customise Title here
customTitle.setText(title);
customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground));
customTitle.setPadding(10, 10, 10, 10);
customTitle.setGravity(Gravity.CENTER);
customTitle.setTextColor(Color.WHITE);
customTitle.setTextSize(20);
builder.setCustomTitle(customTitle)
WebView help = helpContent.findViewById(R.id.helpView);
help.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
String helpText = readRawTextFile(htmlpage); // reads the html file
help.getSettings().setAllowFileAccess(true); // This did not help ...
help.loadData(helpText, "text/html; charset=utf-8", "utf-8");
builder.setView(helpContent); // put view in Dialog box
任何关于正确的帮助、澄清等将不胜感激! 应该添加 html 文件,当在 Windows 中单击时,在浏览器中呈现良好。
【问题讨论】:
-
稍微修改一下就可以了
-
“我正在做的是将 html 文件和图像放在 res/raw 中”——我推荐
assets/。 “需要使用资产目录吗?” -- 我从未尝试过android_res的事情;我看到的几乎所有东西都使用assets/。 “当 WebView 的 html 在与 Activity 不同的对话框中呈现时访问图像,从而使建议的解决方案无效?” -- 不应该。 -
是的,@CommonsWare 的回答会起作用。请尝试让我们知道。
-
@CommonsWare 无赖!我刚试过。创建了一个资产目录,将图像放入其中,并设置 我得到了结果相同。
-
它是
android_asset(单数),而不是android_assets(复数)。 目录 是assets/(复数),但 URL 中的虚假条目是单数。而且,不,我不知道他们为什么那样做...... :-)
标签: android html android-webview