ListView重用旧图片

时间:2016-04-14 17:50:01

标签: android nativescript

我使用Picasso创建了一个插件,并使用android.widget.ImageView将缓存的图片加载到其中。 如果使用Repeater,插件工作正常,但每当我滚动浏览第7个项目后使用ListView时,即使图像源不同,ListView也开始重用旧图像

1 个答案:

答案 0 :(得分:4)

原因是因为列表视图重用了整个片段;所以会发生的事情是你的img被重用会显示旧的图像,除非你清除它。

我实际上自己使用毕加索;这是我现在的毕加索图书馆。 因此,如果您查看下面的代码,当我设置新的.url时,我会清除现有的图像。 (我对特定行做了评论) - 这样图像现在显示为空白,然后毕加索从内存,磁盘或远程网址(在我的情况下是一个远程网址)加载它,它将分配正确的图像。

"use strict";

var Img = require('ui/image').Image;
var application = require("application");

var PT = com.squareup.picasso.Target.extend("Target",{
    _owner: null,
    _url: null,
    onBitmapLoaded: function(bitmap, from) {
        // Since the actual image / target is cached; it is possible that the
        // target will not match so we don't replace the image already seen
        if (this._url !== this._owner._url) {
            return;
        }
        this._owner.src = bitmap;
    },
    onBitmapFailed: function(ed) {
        console.log("Failed File", this._url);
    },
    onPrepareLoad: function(ed) {

    }
});

Object.defineProperty(Img.prototype, "url", {
    get: function () {
        return this._url;
    },
    set: function(src) {
        if (src == null || src === "") {
            this._url = "";
            this.src = null;
            return;
        }
        var dest = src;
        this._url = dest;
        this.src = null; // -- THIS IS THE LINE TO CLEAR THE IMAGE
        try {
            var target = new PT();
            target._owner = this;
            target._url = dest;
            var x = com.squareup.picasso.Picasso.with(application.android.context).load(dest).into(target);
        } catch (e) {
            console.log("Exception",e);
        }
    },
    enumerable: true,
    configurable: true
});

请注意,您只需要要求此课程一次,然后将其自身附加到< Image>组件并添加新的 .url 属性;这允许我在所有其他屏幕中的Declarative XML中使用它,当我需要picasso时,我只使用.url属性让picasso接管该图像的加载。