1

我只是在developer.android.com上阅读从 url 缓存位图的教程

参考代码

    private LruCache<String, Bitmap> mMemoryCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int memClass = ((ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE)).getMemoryClass();

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;

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

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);

    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        mImageView.setImageBitmap(bitmap);
    } else {
        mImageView.setImageResource(R.drawable.image_placeholder);
        BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
        task.execute(resId);
    }
}

在活动缓存中是初始化的,有两种方法

  1. addBitmapToMemoryCache(String key, Bitmap bitmap)

  2. getBitmapFromMemCache(String key)

这是 BitmapWorkerTask 类

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    ...
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        final Bitmap bitmap = decodeSampledBitmapFromResource(
                getResources(), params[0], 100, 100));
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
        return bitmap;
    }
    ...
}

现在我的问题是,在BitmapWorkerTask类中,方法addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); 被调用时对 Activty 中定义的或可能在其他类中的方法有任何引用

4

2 回答 2

2

BitmapWorkerTask 可能是 Activity 中的一个内部类,因此它可以访问定义的方法。

于 2013-01-04T06:39:57.917 回答
0

对于仍然无法使示例代码工作的人,

为了让代码工作,你应该让 BitmapWorkerTask 类成为一个内部类,然后改变它的两个静态函数

public  static int calculateInSampleSize()
public  static Bitmap decodeSampledBitmapFromResource()

正常(非静态)方法

于 2013-08-01T16:55:32.550 回答