0

My Android App has a few screens where the user can tap a button, and help text pops up in a DialogFragment. Currently the text for these DFs is stored in strings.xml, like this:

<string name="help_content">
   <![CDATA[<h1>Welcome</h1>
            <p>Here is some helpful information</p>]]></string>

Obviously, this lets me add styles to the text to make it look better.

In a couple of places, I'd like to explain what some icons do, and I want to include images of the icons, so I'd like to do something like this:

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

Is there a way to include the images so that they use the actual ones from the app? ie something along the lines of getResources().getDrawable(R.drawable.icon_1) or @drawable/icon_1 or something, which can be referenced from the CDATA. I've tried both of those, but got the red error line.

Sharon
  • 3,471
  • 13
  • 60
  • 93
  • 1
    How are you using this HTML? Are you putting it in a `WebView`? Are you using `HtmlCompat.fromHtml()` and putting it in a `TextView`? Or are you trying to put it in a `TextView` directly via `@string/help_content`? – CommonsWare Aug 06 '19 at 11:42
  • 1
    Check [this](https://stackoverflow.com/q/2865452/1679754) – Jignesh Mayani Aug 06 '19 at 11:45
  • I'm using it in a TextView directly, using @string/help_content – Sharon Aug 06 '19 at 18:24

1 Answers1

1

Thanks to the links above, I figured this out. I have my icons saved as drawables, and did the following:

In the help_content string, I put img tags with the name of the required drawable saved as 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>

Then at the point where I add this string to the TextView, I previously had:

mHelpContent.setText(Html.fromHtml(mText));

and have replaced it with:

mHelpContent.setText(Html.fromHtml(mText, new ImageGetter(), null));

I then define the ImageGetter class as follows:

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

This shows the icon as required.

Sharon
  • 3,471
  • 13
  • 60
  • 93