使用齐射时将图像加载到自定义Imageview而不是NetworkImageView

时间:2016-03-28 19:55:17

标签: android-volley networkimageview subsampling

在使用volley从服务器加载图像时,我需要在Pinview而不是本机NetworkImageView中加载图像。

我经历了很多文章但我一无所获。有没有办法这样做?

1 个答案:

答案 0 :(得分:2)

嗯,我不知道是否有人会发现它有用,但以防万一。

我的要求是我需要将图像加载到我需要位图的自定义imageview。

我使用了Singleton类。

public class MyVolleySingleton {

private static MyVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MyVolleySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
    mImageLoader = getImageLoaderRequest();
}
private ImageLoader getImageLoaderRequest() {
    return new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);
                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }
                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            }
    );
}

public static synchronized MyVolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MyVolleySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
    return mImageLoader;
}

}

现在在主要活动中,我使用了我传递了必须加载的图像网址的函数。

    private void loadImage(String plan_url) {
        String url = plan_url;
        if (url.equals("")) {
            Toast.makeText(this, "<Error Message>", Toast.LENGTH_LONG).show();
            return;
        }

        // Retrieves an image specified by the URL, displays it in the UI.
        ImageRequest request = new ImageRequest(url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        imageView.setImage(ImageSource.bitmap(bitmap));

                    }
                }, 0, 0, null,
                new Response.ErrorListener() {
                    public void onErrorResponse(VolleyError error) {
                        imageView.setImage(ImageSource.resource(R.drawable.demo1));
                    }
                });
// Access the RequestQueue through your singleton class.
        MyVolleySingelton.getInstance(this).addToRequestQueue(request);
    }

Volley developer docs