views:

1102

answers:

2

I am throwing HTML to a webview to render. In the HTML I need to load an image that I have in /res/drawable.

I have /res/drawable/my_image.png and code such as this:

final WebView browser = (WebView) findViewById(R.id.my_webview);
String html = new MyHelper(myObject).getHtml();
browser.loadDataWithBaseURL("", html, "text/html", "UTF-8", "");

Where the String html has something like:

<html><head>
<h1>Here is the image</h1>
<img src="my_image.png" />
</head><html>

The question is, what should that image src attribute be to refer to the image in /res/drawable

~Thanks

A: 

I admit I don't know much about WebViews / HTML, but it seems like you're taking the more complicated route for this. There's an easy way to load the HTML file; put it in your assets folder, and then it can be referred to as follows.

WebView webView = new WebView(this);
webView.loadUrl("file:///android_asset/index.html");
setContentView(webView);

Obviously your layout is more complex as you have more than just the WebView so you can't use setContentView() directly, but that's the basic idea. Then to reference an image in that HTML file, I used a <img> tag like so:

<img src="res/drawable/icon.png"/>

Does that work for you?

Steve H
its off topic, but loadUrl is not suitable. I am downloading HTML fragments from one of our applications, decorating that HTML, and then sending the HTML to the view. For this particular use case I am getting HTML that has an object tag to show an FLV. I have to replace that with an anchor tag to the MP4 of the FLV. The anchor tag contains an image, a play button. This play button is the resource I am trying to load.<img src="res/drawable/icon.png"/> does not work.
MikeNereson
Hmm. Strange that <img src...> as described above doesn't work, but it's probably getting confused with where the starting folder is. Anyway, judging from your comments directly to the question, it seems like you found a way to solve this. I'm glad the comment about the assets folder helped, even if I was going down a different track!
Steve H
+1  A: 

Hi,

I have the exact same problem, but neither placing the image file in res/drawable (which I first had to create, I hust had drawable-hdpi, -ldpi and -mdpi already existing) or using the file:///asset/ URL worked for me.

Here is what I do:

Activitity: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    String summary = "<html><body><div style=\"background:red; width:300px; height:50px;\"></div><img src=\"res/drawable/banner300.jpg\"/></body></html>";
    mWebView.loadData(summary, "text/html", "utf-8");

Then in res/drawable I placed the banner300.jpg - but it does not show up. Any ideas?