Android LruCache in ListView

package zhangphil.cache;

import android.app.ListActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class MainActivity extends ListActivity {
    private LruCache mLruCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int CACHE_SIZE = 8 * 1024 * 1024;
        mLruCache = new LruCache(CACHE_SIZE);

        ArrayAdapter mAdapter = new ArrayAdapter(this, 0) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                ImageView image = new ImageView(getContext());
                load(R.mipmap.ic_launcher, image);
                return image;
            }

            @Override
            public int getCount() {
                return 20;
            }
        };

        setListAdapter(mAdapter);
    }

    private void load(int id, ImageView image) {
        Bitmap bmp = mLruCache.get(String.valueOf(id));
        if (bmp == null) {
            Log.d("LruCache缓存", "没有缓存,开始创建新数据资源并缓存之。");
            bmp = BitmapFactory.decodeResource(getResources(), id);
            mLruCache.put(String.valueOf(id), bmp);
        } else {
            Log.d("LruCache缓存", "已有缓存,复用。");
            image.setImageBitmap(bmp);
        }
    }
}

你可能感兴趣的:(Android,android)