继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

通过案例快速学会Picasso图片缓存库

猴子搬来的救兵Castiel
关注TA
已关注
手记 77
粉丝 40
获赞 184

  picasso是Square公司开源的一个Android图形缓存库,官网地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。 
       下载地址:https://github.com/square/picasso

配置方法
MAVEN
<dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>(insert latest version)</version>
</dependency>
GRADLE

compile 'com.squareup.picasso:picasso:(insert latest version)'
基本使用

picasso仅需一行代码就能实现图片的异步加载

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:

  1. 在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。
  2. 使用复杂的图片压缩转换来尽可能的减少内存消耗
  3. 自带内存和硬盘二级缓存功能
Picasso特性

ADAPTER 中的下载:Adapter的重用会被自动检测到,Picasso会取消上次的加载

@Override public void getView(int position, View convertView, ViewGroup parent) {
  SquaredImageView view = (SquaredImageView) convertView;
  if (view == null) {
    view = new SquaredImageView(context);
  }
  String url = getItem(position);

  Picasso.with(context).load(url).into(view);
}

图片转换:转换图片以适应布局大小并减少内存占用

Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

       你还可以自定义转换:

public class CropSquareTransformation implements Transformation {
  @Override public Bitmap transform(Bitmap source) {
    int size = Math.min(source.getWidth(), source.getHeight());
    int x = (source.getWidth() - size) / 2;
    int y = (source.getHeight() - size) / 2;
    Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
    if (result != source) {
      source.recycle();
    }
    return result;
  }

  @Override public String key() { return "square()"; }
}

将CropSquareTransformation 的对象传递给transform 方法即可。

Place holders-空白或者错误占位图片 

picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)//没有加载图片时显示的默认图像
    .error(R.drawable.user_placeholder_error)// 图像加载错误时显示的图像
    .into(imageView);// 被加载的控件

如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder。
 
资源文件的加载 

除了加载网络图片以外,picasso还支持加载Resources, assets, files, content providers中的资源文件。

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);

列表使用Picasso加载图片案例

首先在dependencies 中添加Picasso相关配置

compile ‘com.squareup.picasso:picasso:2.5.2’

然后上源码:

ListViewActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表Activity
 */
public class ListViewActivity extends AppCompatActivity {

    private ListView lv_main;
    private List<SunBean> listDatas;
    private SunAdapter lAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view);
        lv_main = (ListView) findViewById(R.id.list_sun);
        listDatas = new ArrayList<>();
        initData();
        lAdapter = new SunAdapter(listDatas, this);
        lv_main.setAdapter(lAdapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        SunBean sun1 = new SunBean();
        sun1.setTitle("太阳的后裔一");
        sun1.setPicUrl("http://img3.imgtn.bdimg.com/it/u=3746050745,4184822198&fm=11&gp=0.jpg");
        listDatas.add(sun1);

        SunBean sun2 = new SunBean();
        sun2.setTitle("太阳的后裔二");
        sun2.setPicUrl("http://cdn.duitang.com/uploads/item/201603/02/20160302223503_jmdXT.thumb.224_0.jpeg");
        listDatas.add(sun2);

        SunBean news3 = new SunBean();
        news3.setTitle("太阳的后裔三");
        news3.setPicUrl("http://img5.duitang.com/uploads/item/201602/23/20160223132131_RNSQ3.thumb.224_0.jpeg");
        listDatas.add(news3);

        SunBean sun4 = new SunBean();
        sun4.setTitle("太阳的后裔四");
        sun4.setPicUrl("http://img5.duitang.com/uploads/item/201603/03/20160303163634_iveUE.thumb.224_0.jpeg");
        listDatas.add(sun4);

        SunBean sun5 = new SunBean();
        sun5.setTitle("太阳的后裔五");
        sun5.setPicUrl("http://cdn.duitang.com/uploads/item/201603/07/20160307013640_FQCTc.thumb.224_0.jpeg");
        listDatas.add(sun5);

        SunBean sun6 = new SunBean();
        sun6.setTitle("太阳的后裔六");
        sun6.setPicUrl("http://img4.duitang.com/uploads/item/201603/03/20160303102359_vzwPC.thumb.224_0.jpeg");
        listDatas.add(sun6);

        SunBean news7 = new SunBean();
        news7.setTitle("太阳的后裔七");
        news7.setPicUrl("http://img4.duitang.com/uploads/item/201603/03/20160303101132_AMPRv.thumb.224_0.jpeg");
        listDatas.add(news7);

        SunBean sun8 = new SunBean();
        sun8.setTitle("太阳的后裔八");
        sun8.setPicUrl("http://img0.imgtn.bdimg.com/it/u=1043934750,464206674&fm=11&gp=0.jpg");
        listDatas.add(sun8);
    }

}

SunAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表Adapter
 */
public class SunAdapter extends BaseAdapter {

    private List<SunBean> list_sun;
    private LayoutInflater inflater;
    private Context context;

    public SunAdapter(List<SunBean> list_new, Context context) {
        this.list_sun = list_new;
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

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

    @Override
    public Object getItem(int position) {
        return list_sun.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ItemViewHodler viewHolder;
        if (convertView == null) {
            viewHolder = new ItemViewHodler();

            convertView = inflater.inflate(R.layout.list_item, null);
            viewHolder.title = (TextView) convertView.findViewById(R.id.item_title);
            viewHolder.pic = (ImageView) convertView.findViewById(R.id.item_pic);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ItemViewHodler) convertView.getTag();
        }

        viewHolder.title.setText(list_sun.get(position).getTitle());
        Picasso.with(context).load(list_sun.get(position).getPicUrl()).fit()
                .placeholder(R.mipmap.alibg)
                .error(R.mipmap.ic_launcher)
                .into(viewHolder.pic);

        return convertView;
    }

    class ItemViewHodler {
        TextView title;
        ImageView pic;
    }
}

SunBean.java

/**
 * Created by huangshuai on 2016/5/20.
 * Email:huangshuai@wooyun.org
 * 列表图片Bean
 */
public class SunBean {

    private String title;
    private String picUrl;

    public SunBean(String title, String picUrl) {
        this.title = title;
        this.picUrl = picUrl;
    }

    public SunBean() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
}

list_itmxml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="太阳的后裔" />

    <ImageView
        android:id="@+id/item_pic"
        android:layout_width="160dp"
        android:layout_height="240dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/item_title"
        android:src="@mipmap/alibg" />

</RelativeLayout>

list_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list_sun"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</RelativeLayout>

最后不要忘了增加网络权限

<uses-permission android:name="android.permission.INTERNET" />
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP