用Picasso从url加载多个Imageview?

时间:2014-05-04 23:30:15

标签: android android-layout image-loading picasso

我正在尝试使用Picasso加载多个ImageView,但它只加载一个ImageView。 HEre是我的代码:

    public void setClassicImg(JSONArray listImg, RelativeLayout rl) throws JSONException, IOException, MalformedURLException {
    if (listImg.length() > 0)
    {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        for (int i = 0; i < listImg.length(); i++) 
        {

            ImageView downloadedImg = new ImageView(this);
                            //  downloadedImg.setBackgroundColor(Color.parseColor(listImg.getJSONObject(i).getString("color")));
            //      new DownloadImageTask(downloadedImg).execute(listImg.getJSONObject(i).getString("http"));

            Picasso.with(this.getApplicationContext()).load(listImg.getJSONObject(i).getString("http")).into(downloadedImg);

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) (metrics.widthPixels * listImg.getJSONObject(i).getDouble("size_x")), (int) (metrics.heightPixels * listImg.getJSONObject(i).getDouble("size_y")));
            params.leftMargin = (int) (metrics.widthPixels * listImg.getJSONObject(i).getDouble("position_x"));
            params.topMargin = (int) (metrics.heightPixels * listImg.getJSONObject(i).getDouble("position_y"));
            downloadedImg.setScaleType(ImageView.ScaleType.FIT_XY);
            //              downloadedImg.getLayoutParams().width = BIND_ALLOW_OOM_MANAGEMENT;


            /// downloadedImg.setBackgroundDrawable(animation);
            //                  downloadedImg.setImageDrawable(animation);
            rl.addView(downloadedImg, params);
        }
    }
}

我正在解析json文件。包含Image的.png或.jpg的字符串在String http中,所以我得到它但是在设备上,它只显示第一个加载的ImageView,好像它是循环一次。

任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,Picasso只是加载了第一个,在我的情况下,我的解决方案是创建一个自定义类来处理它,所以我将URL存储在List中,当它结束加载时我开始加载下一个。并且不要慢,我加载了没有目标的所有东西,所以它缓存了图像。

@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
    //DO whatever you need with the bitmap
    urls.remove(currentUrl);
    if (urls.size() > 0) {
        currentUrl = urls.get(0);
        Picasso.with(context).load(urls.get(0)).into(this);
    }
}

和我添加网址的方法

public void addUrl(String url) {
    urls.add(url);
    if (currentUrl.isEmpty()) {
        //this would be the first Url, so load directly
        currentUrl = url;
        Picasso.with(context).load(url).into(this);
    }
    else {
        //load to cache, than when loaded into the target it will get from memory
        Picasso.with(context).load(url);
    }
}