Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

android - Recycler view with volley image request (cancel request)

So i am using recycler view to show images in a grid and downloading images from url as bitmaps using volley library.

public void onBindViewHolder(final TrendingAdapter.ViewHolder viewHolder, int i) {
    ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            if (bitmap != null) {
                viewHolder.getmImageView().setImageBitmap(bitmap);
            }
        }
    }, 0, 0, null,
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
    AppController.getInstance().addToRequestQueue(request);
}

The problem is when i scroll and skip one or more views before the image is downloaded and that view is recycled the image donwnload reqest is not canceled on those intermediate view resulting in a flash of that/those image(s) before the actual image is loaded in that view.

So i thought of canceling those intermediate image requests using tags but cannot figure out how as it results in canceling of request in other parallel views as well!

Also when i use volley NetworkImageView (that handels such image canceling by itself) gives perfect results. But i need to get bitmap of every image to pick colors from it so i cannot use NetworkImageView.

Q) How do i cancel all pending volley image requsts (except the one it should be loading and without effecting other parallel views) on a specific imageview inflated using recyclerview?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the ImageLoader class instead of directly adding a request to the RequestQueue. That way, the get() method, which is used to get images, will return an object of type ImageContainer.

Save this ImageContainer in the ViewHolder, and when a view gets recycled, simply call the cancelRequest() method on the recycled image to cancel the request if it hasn't been performed yet.

Take a look at the NetworkImageView's code. It works in a similar way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...