I am building a gallery using a ViewPager. Every time a photo is downloaded I immediately cache it in mMemoryCache which is

mMemoryCache = new LruCache<Integer, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(Integer key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number
            // of items.
            return (bitmap.getRowBytes() * bitmap.getHeight());
        }
    };

As you can see sizeOf() returns the number if bytes used, which makes sense. My problem is that my ViewPager's adapter needs to know how many pages I have, which would be the number of objects in my cache.

Any ideas on how I can do it? thanks!

有帮助吗?

解决方案

I think you should rethink your approach. Usually, when you use some kind of paging (i mean data paging, not the ViewPager), you first add a certain fixed number of items to your Adapter. You can either start downloading the required resources right away, or wait until you really need them. Check in Adapter.onCreateView() if the resource is already downloaded and cached. If yes, get it from there, if not, start an asynchronous download and add the image to the view as soon as you got it. Show a placeholder in the meantime.

When you reach the last item in your adapter, add another batch to it and everything starts over again.

If you really want to know what items are in your LRUCache, override put() and entryRemoved(). There you know what items get added or evicted from the cache. I would advise against this method though.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top