Search code examples
androidimageandroid-2.3-gingerbread

Internet url as Android ImageSpan source


is it possible to specify internet url for ImageSpan and get it shown with TextView? I've tried quite a few versions of

String mockContent = "<img src=\"http://www.google.com/intl/en_com/images/srpr/logo3w.png\">";
myTextView.setText(Html.fromHtml(mockContent), BufferType.SPANNABLE);

but that results in the generic not found image (blueish black bordered square).

Do I have to download the image first, then replace all the urls and so on? Knowing the new C# is capable of handling such resources, I hoped Android might meet my hopes here.

Using API version 10: 2.3.3.


Solution

  • If you have the image source locally then it should work or else use,

    Html.fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
    

    Returns displayable styled text from the provided HTML string.

    Nice example I found on web,

    String s = Html.fromHtml(htmlContent, new ImageGetter() { 
            @Override
         public Drawable getDrawable(String source) {                   
    
            // Code for getting image either by download or using static iamge
    
             Drawable d = null;
            try { 
                        InputStream src = imageFetch(source); 
                        d = Drawable.createFromStream(src, "src");
                        if(d != null){
                           d.setBounds(0,0,(d.getIntrinsicWidth(),
                           d.getIntrinsicHeight());
                        }
                } catch (MalformedURLException e) { 
                  e.printStackTrace();  
                } catch (IOException e) {
                  e.printStackTrace();   
       } 
    
    
        return d;
        } 
    
    
      },null);
    

    For more info Html.fromHtml with ImageGetter.