android - 如何在代表 HTML 的 CDATA 字符串中包含图像?
问题描述
我的 Android 应用程序有几个屏幕,用户可以在其中点击一个按钮,并在 DialogFragment 中弹出帮助文本。目前,这些 DF 的文本存储在 strings.xml 中,如下所示:
<string name="help_content">
<![CDATA[<h1>Welcome</h1>
<p>Here is some helpful information</p>]]></string>
显然,这让我可以为文本添加样式以使其看起来更好。
在几个地方,我想解释一些图标的作用,我想包括图标的图像,所以我想做这样的事情:
<string name="help_content">
<![CDATA[<h1>Welcome</h1>
<p><img src="path/to/icon1"> This is what Icon 1 does</p>
<p><img src="path/to/icon2"> This is what Icon 2 does</p>]]></string>
有没有办法包含图像,以便它们使用应用程序中的实际图像?即可以从 CDATA 中引用的类似于getResources().getDrawable(R.drawable.icon_1)
or或 something 的东西。@drawable/icon_1
我已经尝试了这两种方法,但得到了红色错误线。
解决方案
感谢上面的链接,我想通了。我将我的图标保存为可绘制对象,并执行了以下操作:
在 help_content 字符串中,我将带有所需可绘制对象名称的 img 标签保存为 src:
<string name="help_content">
<![CDATA[<h1>Welcome</h1>
<p><img src="icon1"> This is what Icon 1 does</p>
<p><img src="icon2"> This is what Icon 2 does</p>]]></string>
然后在我将此字符串添加到 TextView 时,我之前有:
mHelpContent.setText(Html.fromHtml(mText));
并将其替换为:
mHelpContent.setText(Html.fromHtml(mText, new ImageGetter(), null));
然后我定义 ImageGetter 类如下:
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id;
if((source == null) || (source.equals(""))) {
return null;
}else {
id = mContext.getResources().getIdentifier(
source,
"drawable",
mContext.getPackageName()
);
if(id != 0) {
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0,
d.getIntrinsicWidth(),
d.getIntrinsicHeight());
return d;
}else return null;
}
}
}
这将根据需要显示图标。
推荐阅读
- android - Flutter:根据情况在文字上使用不同的颜色
- excel - Dir gets me a filepath, but then I can't open it or read a timestamp
- kivy - 如何在不重新输入代码 kivymd 的情况下重新使用 MDNavigationDrawer
- scala - 列出 sbt `Task` 标签
- javascript - 如何在 JS 中获取 TSV 文件并转换为 JSON
- java - 无法通过 Googles Nearby API 连接两台设备
- c# - 如何在为其设置值时检查动态属性的数据类型?
- c++ - ${workspaceFolder}\\*.cpp 显然没有被识别为 vscode tasks.json 中的有效路径
- makefile - 包括来自父目录的标题
- excel - VBA - 删除包含较少信息的重复项