通过案例快速学会Android Picasso图片缓存库
imud86
9年前
<p> picasso是Square公司开源的一个Android图形缓存库,官网地址<a href="/misc/goto?guid=4958860113958143127">http://square.github.io/picasso/</a>,可以实现图片下载和缓存功能。<br> 下载地址:<a href="/misc/goto?guid=4958972548258164558">https://github.com/square/picasso</a></p> <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/dc024edaaabe3e9838d6296d3cc40b6e.png"></p> <h2>配置方法</h2> <pre> <code class="language-java">MAVEN <dependency> <groupId>com.squareup.picasso</groupId> <artifactId>picasso</artifactId> <version>(insert latest version)</version> </dependency></code></pre> <pre> <code class="language-java">GRADLE compile 'com.squareup.picasso:picasso:(insert latest version)'</code></pre> <h2>基本使用</h2> <p> picasso仅需一行代码就能实现图片的异步加载</p> <pre> <code class="language-java">Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);</code></pre> <p> Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:</p> <ol> <li>在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。</li> <li>使用复杂的图片压缩转换来尽可能的减少内存消耗</li> <li>自带内存和硬盘二级缓存功能</li> </ol> <h2>Picasso特性</h2> <p><strong>ADAPTER 中的下载:Adapter的重用会被自动检测到,Picasso会取消上次的加载</strong></p> <pre> <code class="language-java">@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); }</code></pre> <p><strong>图片转换:转换图片以适应布局大小并减少内存占用</strong></p> <pre> <code class="language-java">Picasso.with(context) .load(url) .resize(50, 50) .centerCrop() .into(imageView)</code></pre> <p> 你还可以自定义转换:</p> <pre> <code class="language-java">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()"; } }</code></pre> <p> 将CropSquareTransformation 的对象传递给transform 方法即可。</p> <p><strong>Place holders-空白或者错误占位图片</strong><br> picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。</p> <pre> <code class="language-java">Picasso.with(context) .load(url) .placeholder(R.drawable.user_placeholder)//没有加载图片时显示的默认图像 .error(R.drawable.user_placeholder_error)// 图像加载错误时显示的图像 .into(imageView);// 被加载的控件</code></pre> <p> 如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder。<br> <strong>资源文件的加载</strong><br> 除了加载网络图片以外,picasso还支持加载Resources, assets, files, content providers中的资源文件。</p> <pre> <code class="language-java">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);</code></pre> <p><strong>列表使用Picasso加载图片案例</strong></p> <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/3e6f95695d598c446a6a3eea8e56e3e2.png"></p> <p>首先在dependencies 中添加Picasso相关配置</p> <p><strong>compile ‘com.squareup.picasso:picasso:2.5.2’</strong></p> <p>然后上源码:</p> <p>ListViewActivity.java</p> <pre> <code class="language-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); } }</code></pre> <p>SunAdapter.java</p> <pre> <code class="language-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; } }</code></pre> <p>SunBean.java</p> <pre> <code class="language-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; } }</code></pre> <p>list_itmxml</p> <pre> <code class="language-java"><?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></code></pre> <p>list_view.xml</p> <pre> <code class="language-java"><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></code></pre> <p>最后不要忘了增加网络权限</p> <pre> <code class="language-java"><uses-permission android:name="android.permission.INTERNET" /> </code></pre> <p>来自: <a href="/misc/goto?guid=4959673479396853621" rel="nofollow">http://blog.csdn.net/mynameishuangshuai/article/details/51462601</a></p> <p> </p>