Can any one help me out how to use Html.ImageGetter to dispaly images using html image src tag ? and example or good tutorial
4 Answers
To get images from the application resources first in the text file one inserts an html image tag like this:
<img src="my_image">
Note that "my_image" is just a name of a drawable not a path. Then use this code to diplay the text with images in TextView
myTextView.setText(Html.fromHtml(myText, new ImageGetter() {
@Override public Drawable getDrawable(String source) {
Drawable drawFromPath;
int path =
myActivity.this.getResources().getIdentifier(source, "drawable",
"com.package...");
drawFromPath = myActivity.this.getResources().getDrawable(path);
drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(),
drawFromPath.getIntrinsicHeight());
return drawFromPath;
}
}, null));
If the source in the img tag is misspelled the applicaiton will crash because the method will fail to find the drawable, so more code can be added to prevent this...
-
So we should be MORE careful about image name for example NOT flower.jpg it should be flower – mehmet Jun 09 '14 at 19:45
Here is the same as the accepted answer, but as a top level class (which is nicer if you want to use it from different places):
public class ResourceImageGetter implements ImageGetter {
private Context mContext;
public ResourceImageGetter(Context context) {
mContext = context;
}
@Override
public Drawable getDrawable(String source) {
Resources resources = mContext.getResources();
int identifier = resources.getIdentifier(source, "drawable", mContext.getPackageName());
Drawable res = resources.getDrawable(identifier);
res.setBounds(0, 0, res.getIntrinsicWidth(), res.getIntrinsicHeight());
return res;
}
}

- 10,838
- 6
- 63
- 59
The answer from kape123 certainly helped me. I was so nearly there.
The bit that's easy to miss is the call to setBounds on the Drawable. The Html.ImageGetter help documentation also provides a clue when it says:
Make sure you call setBounds() on your Drawable if it doesn't already have its bounds set.

- 610
- 6
- 13
-
The slightly aggravating part is how they don't exactly tell you *how* to do so. Why it does not default to the intrinsic values is also beyond me. – Erik Aug 11 '14 at 16:43
-
I had the same problem. ie not having set the bounds. Just a thought, couldn't they throw an exception so that we can figure this out sooner? – George Daramouskas Jun 22 '15 at 12:22
textView.setText(Html.fromHtml(htmlToSetAsText, new ImageGetter() { @Override public Drawable getDrawable(String source) { String path = "/sdcard/" + source; Drawable bmp = Drawable.createFromPath(path); bmp.setBounds(0, 0, bmp.getIntrinsicWidth(), bmp.getIntrinsicHeight()); return bmp; } }, null));

- 20,366
- 24
- 120
- 181