如何在代表 HTML 的 CDATA 字符串中包含图像?

How do I include an image in a CDATA string which represents HTML?

我的 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>

有没有办法包含图像,以便它们使用应用程序中的实际图像?即类似于 getResources().getDrawable(R.drawable.icon_1)@drawable/icon_1 之类的东西,可以从 CDATA 中引用。这两个我都试过了,但出现了红色错误行。

感谢上面的链接,我明白了。我将图标保存为可绘制对象,并执行了以下操作:

在 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 class 如下:

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

这显示了所需的图标。