Use a thumbnail as a placeholder for Picasso

后端 未结 3 1465
太阳男子
太阳男子 2021-02-02 03:49

From the UX point of view, it will be great to show the user a thumbnail first until the real image completes loading, then showing it to him, but Picasso uses only a resource f

3条回答
  •  Happy的楠姐
    2021-02-02 04:34

    I originally used AbdelHady's solution but found that the larger image is only loaded after the thumbnail is done loading so I came up with this instead.

    Assuming you have a utility class in your project;

    public final class U {
    
    public static void picassoCombo(final RequestCreator thumbnail,
                                    final RequestCreator large,
                                    final ImageView imageView) {
        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                imageView.setImageBitmap(bitmap);
            }
    
            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                imageView.setImageDrawable(errorDrawable);
            }
    
            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                thumbnail.into(imageView);
            }
        };
    
        imageView.setTag(target); // To prevent target from being garbage collected
        large.into(target);
    }
    }
    

    Usage:

    U.picassoCombo(
            Picasso.with(context)
                    .load("http://lorempixel.com/200/100/sports/1/")
                    .placeholder(R.drawable.ic_image_placeholder),
            Picasso.with(context)
                    .load("http://lorempixel.com/800/400/sports/1/")
                    .error(R.drawable.ic_image_broken),
            imageView
    );
    

    In the above example the placeholder is set first, the thumbnail url is set next, and regardless of whether the thumbnail request is done, successful, or failed, the large image request is set once it is done. If the large image request failed, then the error drawable is set.

    The only issue is that if you use setIndicatorsEnabled(true) the debug indicators don't show for the large request. As far as I can tell this seems to be by design according to this issue convo

提交回复
热议问题