三级缓存

  • Post author:
  • Post category:其他


1、三级缓存是指:网络、 内存、 SD卡三级;

展示一张图片

1、先判断内存里是否有该图片,

如果有,显示。如果没有,进入第二步

2、判断SD卡中是否有该图片,如果有,

加载到内存中,显示,如果没有,进入第三步

3、从网络下载该图片到sd卡中,并且加载到内存中。然后显示。

2、利用三级缓存来实现一个listView的图片展示,代码如下:

实现的原理如图所示:

MainActivity:

public class MainActivity extends AppCompatActivity {
    ListView listvew;
    ArrayList<String> urlList;
    ShowImageAdapter2 showImageAdapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listvew = (ListView) findViewById(R.id.listvew);
        initList();

        showImageAdapter2 = new ShowImageAdapter2(urlList, this);
        listvew.setAdapter(showImageAdapter2);
    }

    private void initList() {
        urlList = new ArrayList<>();
        for (int i = 1; i < 200; i++){
            String url = "http://img2.3lian.com/2014/f4/100/d/" + i + ".jpg";
            urlList.add(url);
        }
    }
}
 

ShowImageAdapter2:

public class ShowImageAdapter2 extends BaseAdapter {
    ArrayList<String> list;
    LayoutInflater layoutInflater;
    Context context;
    public ShowImageAdapter2(ArrayList<String> list, Context context) {
        this.list = list;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public String getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //每次Item的展示都需要实例化viewHolder或者从服用的convertView中取出实例化好的ViewHolder
        ViewHolder viewHolder = null;
        if (convertView == null){
            convertView = layoutInflater.inflate(R.layout.item_imagview, null);
            viewHolder = new ViewHolder();
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
            convertView.setTag(viewHolder);
        }else {
            viewH



版权声明:本文为yshunb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。