【问题标题】:Async ImageGetter not functioning properly异步 ImageGetter 无法正常运行
【发布时间】:2011-12-06 01:56:58
【问题描述】:

我试图从 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 );
    }
}

【问题讨论】:

  • 我不知道你在问什么。 IE 在这里做什么?
  • IE 是正在下载到我的应用程序中的屏幕截图。我希望你能分辨出两张照片之间的区别。问题是当异步下载图片时,它们都被混合在一起,而我正在寻找的是第二张图片上显示的内容。
  • 这与下载无关!您以错误的方式布局它们
  • 好的。所以实际内容是不相关的,只是图像不同的事实?
  • 贴几行代码可能会有帮助。

标签: android html-parsing android-asynctask textview


【解决方案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 重新布局其内容。

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多