我试图按照此主题中的信息异步下载来自html的内嵌图像:Android HTML ImageGetter as AsyncTask
我可以让图片下载好。但是!
这就是最终结果:
如果我不以异步方式下载它们,它应该看起来如何以及它看起来如何:
有关如何解决此问题的任何想法? 提前谢谢。
编辑:
我的URLImageParser代码:
public URLImageParser( View 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 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight() );
urlDrawable.drawable = result;
URLImageParser.this.container.invalidate();
}
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 Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet( urlString );
HttpResponse response = httpClient.execute( request );
return response.getEntity().getContent();
}
}
和URLDrawable的代码
@Override
public void draw( Canvas canvas )
{
if( drawable != null )
{
drawable.draw( canvas );
}
}
答案 0 :(得分:1)
我找到了解决此问题的方法。 您必须保留对TextView实例的引用,并且在下载图像后,您必须使用onPostExecute方法中的相同文本调用setText:
@Override
protected void onPostExecute( Drawable result )
{
urlDrawable.setBounds( 0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight() );
urlDrawable.drawable = result;
// mTextView is the reference to the TextView instance
mTextView.setText(mTextView.getText());
}
这会强制TextView重新布局其内容。