【问题标题】:Fetching Remote Images Asynchrounously for an ImageAdapter为 ImageAdapter 异步获取远程图像
【发布时间】:2011-06-08 09:41:59
【问题描述】:

我有一个用于 getView() 的 Android Gallery ImageAdapter 实现,如下所示:

public View getView(int arg0, View arg1, ViewGroup arg2) {
    String strURL = "http://app1.exactdev.co.za/android/celebs/celeb" + (arg0+1) + ".jpg";      
    Bitmap bm = RemoteBitMapHelper.getRemoteBitMap(strURL); //synchronous request               

    ImageView i = new ImageView(ctx);       
    i.setImageBitmap(bm); 
    return i;
}

如何让 getView 异步完成其工作?

【问题讨论】:

    标签: android multithreading asynchronous galleryview


    【解决方案1】:

    简单的答案是您可以将它放在 AsyncTask 中。类似于以下内容(未经测试)

    public View getView(int arg0, View arg1, ViewGroup arg2) {
    
        final ImageView i = new ImageView(ctx);
        String url = "http://app1.exactdev.co.za/android/celebs/celeb" + (arg0 + 1) + ".jpg";
    
        new AsyncTask<String, Void, Bitmap>() {
    
            @Override
            protected Bitmap doInBackground(String... urls) {
                return RemoteBitMapHelper.getRemoteBitMap(urls[0]);
            }
    
            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    i.setImageBitmap(result);
                }
            }
    
        }.execute(url);
    
        return i;
    }
    

    【讨论】:

    • 并没有像我希望的那样真正提高我的画廊表现,但这就像我所期望的那样,就像一个魅力!快速实现了一个简单的公共静态 Map picsMap = new HashMap() 来缓存已经下载的图像,性能提高了 300%。非常感谢!
    • 我正在慢慢了解一切如何与 Android api 一起使用。这个答案很有帮助。
    • getView 可以为同一个项目多次调用:stackoverflow.com/questions/2618272/…
    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多