OOM when using NetworkImageView ( of Volley library)

后端 未结 2 1314
暗喜
暗喜 2020-12-29 16:07

Background

Using the Volley library\'s NetworkImageView is a convenient way to handle showing images from the web.

However, it has some bugs (as i\'ve writ

2条回答
  •  情话喂你
    2020-12-29 16:08

    I found a better solution in my search : -)

    NetworkImageView knows its width at line no - 104 and height at line no - 105 in the link NetworkImageView.java

    Below is the exact code at NetworkImageView.java

        private void loadImageIfNecessary(final boolean isInLayoutPass) {
        int width = getWidth(); // at line no 104
        int height = getHeight(); // at line no 105
    

    you only need to forward this information to the image loader.

    On line 141 NetworkImageView.java calls the ImageLoader#get(String requestUrl, final ImageListener listener) method without width and height. Change this call to ImageLoader#get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight).

    Replace the code from line no 141 to 172 of NetworkImageView.java with below code

    ImageContainer newContainer = mImageLoader.get(mUrl,
                new ImageListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (mErrorImageId != 0) {
                            setImageResource(mErrorImageId);
                        }
                    }
    
                    @Override
                    public void onResponse(final ImageContainer response, boolean isImmediate) {
                        // If this was an immediate response that was delivered inside of a layout
                        // pass do not set the image immediately as it will trigger a requestLayout
                        // inside of a layout. Instead, defer setting the image by posting back to
                        // the main thread.
                        if (isImmediate && isInLayoutPass) {
                            post(new Runnable() {
                                @Override
                                public void run() {
                                    onResponse(response, false);
                                }
                            });
                            return;
                        }
    
                        if (response.getBitmap() != null) {
                            setImageBitmap(response.getBitmap());
                        } else if (mDefaultImageId != 0) {
                            setImageResource(mDefaultImageId);
                        }
                    }
                }, width, height);
    

提交回复
热议问题