android - BitmapFun 示例存在缓存问题

标签 android caching bitmap

我正在使用 Android BitmapFun 示例代码来管理我的应用程序中的位图。我一直在 ViewPager 中遇到乱码或重复图像。我已将其追溯到 ImageCache.java 中的以下代码:

           /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key,
                    BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it 
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap
                        // to a SoftRefrence set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

位图在从缓存中移除时被添加到可重用位图列表中。在这种情况下,位图仍由 ViewPager View 使用。当稍后的 View 被创建时,位图(仍在使用中)被重新使用并且位图出现在 ViewPager 中的两个位置。

从 LruCache 中删除的位图不一定可以重用。我已禁用此代码中位图的重用,并且不再有问题。较低分辨率的图像不会出现此问题,因为位图在 ViewPager 的屏幕外限制范围内时不会从缓存中删除。我对 60 DPI 图像没有问题,但在 160 DPI 时经常看到这个问题。我认为这会出现在具有更高分辨率图像的原始 BitmapFun 示例中。

还有其他人遇到过这个问题还是我没有正确理解这个问题?

凯文

最佳答案

我认为代码的问题是在行

mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));

该行将从 LRU 缓存中删除的位图添加到可重用位图集以用于 inBitmap 重用。它不会检查它是否仍在被 ImageView 使用。如果您尝试重新使用 ImageView 仍在使用的位图,底层位图将被替换为另一个位图,使其不再有效。我的建议是在将位图添加到可重用位图集之前跟踪它是否仍在被 ImageView 使用。我创建了一个示例 github project对于这个问题。告诉我您对我的解决方案的看法。

关于android - BitmapFun 示例存在缓存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19166616/

相关文章:

android - 微调器的 Onitemclicklistner 如何将 id 传递给 android 中的下一个微调器

c++ - 如何在 C++ 中将窗口的屏幕截图作为位图对象?

android - 如何将 Drawable 转换为位图?

android - 使用 Ant/Ivy 构建 Android 项目

android - 使用自定义 xml View 在 Android 中创建一个 AlertDialog

java - 使用倒数计时器

java - java.lang.String 的哈希码真的被缓存了吗?

caching - Symfony 1.4 功能测试不显示新数据

java - JPA Eclipselink 数据库更改通知不会使缓存条目无效

c - 如何在C中的窗口上显示两个位图图像