picasso - load image into imagebutton in adapter

馋奶兔 提交于 2019-12-11 11:28:06

问题


I want to load an image into a ImageButton in an adapter, this is sometimes not working... I have a adapter with 4 entries, and sometimes, the button image is just loaded 2 times instead of 4 times. Always only on the first creation of the adapter... After screen rotation or so, everything works fine... But on the first display, it does not work correctly...

The adapter with 4 rows calls 2 times prepare and two times loaded on the first creation only...

Following is my adapter's getView:

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    if (convertView == null)
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_link, parent, false);

    convertView.setTag(R.id.tag_pos, position);

    ImageView iconRow = ViewHolder.get(convertView, R.id.icon);
    final ImageButton btOpen = ViewHolder.get(convertView, R.id.btOpen);

    // this NEVER fails
    PicassoTools.getPicasso().load(item.getIconResId()).into(iconRow);
    // this sometimes (at the first start) does not work reliable
    PicassoTools.getPicasso().load(isAutoLinked ? R.drawable.linked : R.drawable.unlinked).into(new Target()
    {
        @Override
        public void onPrepareLoad(Drawable d)
        {
            L.d(this, "BUTTON PREPARE");
        }

        @Override
        public void onBitmapLoaded(Bitmap b, LoadedFrom loadedFrom)
        {
            L.d(this, "BUTTON LOADED");
            btLink.setImageBitmap(b);
        }

        @Override
        public void onBitmapFailed(Drawable d)
        {
            L.d(this, "BUTTON FAILED");
            btLink.setImageBitmap(null);
        }
    });

    return convertView;
}

My PicassoTools function (I have some extra functions in this class):

public static Picasso getPicasso()
{
    if (picasso == null)
        picasso = new Picasso.Builder(MainApp.getAppContext()).memoryCache(getCache()).build();
    return picasso;
}

回答1:


Use Target

private Target loadtarget;

Write this code in getView()

if (loadtarget == null)
    loadtarget = new Target() {
        @Override
        public void onBitmapFailed(Drawable arg0) {
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
            handleLoadedBitmap(bitmap);
        }

        @Override
        public void onPrepareLoad(Drawable arg0) {

        }
    };

try {
    Picasso.with(this).load(url).into(loadtarget);
} catch (IllegalArgumentException iae) {
    iae.printStackTrace();
}

public void handleLoadedBitmap(Bitmap b) {
    BitmapDrawable bdrawable = new BitmapDrawable(b);
    imageButton.setBackgroundDrawable(bdrawable);
}

Hope this will help you :)



来源:https://stackoverflow.com/questions/26710519/picasso-load-image-into-imagebutton-in-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!