I'm making an application for a blog. Articles in the blog may contain images in between text. To achieve this I used URLImageParser class which extends ImageGetter to bind Images to Textview. I'm able to append Images, but the size of the Image is varying.
When I open the Image in browser, I can see a larger pic, but in my application I'm getting smaller width and height. How do I adjust the width and height based on the Image size from Browser.
URLImageParser class:
public class URLImageParser implements ImageGetter {
Context c;
TextView container;
int width;
public URLImageParser(TextView t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable);
asyncTask.execute(source);
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
urlDrawable.setBounds(0, 0, 0+width, 0+result.getIntrinsicHeight());
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
// For ICS
URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));
}
else
{
// Pre ICS
URLImageParser.this.container.setEllipsize(null);
}
container.setText(container.getText());
}
public Drawable fetchDrawable(String urlString) {
try
{
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0 + drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
Binding it to the TextView:
URLImageParser p = new URLImageParser(tvArticle, this);
Spanned htmlSpan = Html.fromHtml(x+y, p, null);
tvArticle.setText(htmlSpan);
tvArticle.setMovementMethod(LinkMovementMethod.getInstance());
Screenshots of Image my app and Browser: