Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.ImageGetter

Tags:

html

android

Can any one help me out how to use Html.ImageGetter to dispaly images using html image src tag ? and example or good tutorial

like image 444
d-man Avatar asked Nov 24 '09 20:11

d-man


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

like image 146
Lumis Avatar answered Nov 18 '22 01:11

Lumis


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;
    }
}
like image 20
BoD Avatar answered Nov 18 '22 02:11

BoD


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.

like image 5
Quintin Willison Avatar answered Nov 18 '22 02:11

Quintin Willison


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));
like image 1
nikib3ro Avatar answered Nov 18 '22 01:11

nikib3ro