寫一篇利用Picasso圖片加載框架兑凿,PhotoView圖片縮放控件以及ViewPager的圖片瀏覽器
首先建立依賴:
在這里我們加入PhotoView和picasso的依賴
//PhotoView
compile 'com.github.chrisbanes.photoview:library:+'
//picasso
compile 'com.squareup.picasso:picasso:+'
然后我們寫一個圖片列表展示的首頁
圖片的展示頁采用RecyclerView去展示,布局文件如下所示
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
加入數(shù)據(jù)间学,圖片是從網(wǎng)上找的幾張圖片,加入數(shù)據(jù)集合中
images.add("http://img3.imgtn.bdimg.com/it/u=3993672553,267575750&fm=21&gp=0.jpg");
images.add("http://img5.imgtn.bdimg.com/it/u=2652905594,2769975769&fm=21&gp=0.jpg");
images.add("http://i.zeze.com/attachment/forum/201511/06/180208mwwxx8oer7wirv89.jpg");
images.add("http://imgsrc.baidu.com/forum/w%3D580/sign=fe8a7e7f78ec54e741ec1a1689399bfd/4b3f9682d158ccbfb334467b1ad8bc3eb33541cd.jpg");
images.add("http://static.wgpet.com/editor/attached/image/20141124/20141124225933_71813.jpg");
images.add("http://v1.qzone.cc/pic/201405/25/13/57/5381864e3b8af886.jpg%21600x600.jpg");
images.add("http://wanzao2.b0.upaiyun.com/system/pictures/23660313/original/8d4f08e50be02ae3.png");
images.add("http://zyline-photo.qiniudn.com/1392705051156.jpg");
為RecyclerView創(chuàng)建Adapter改抡,在ViewHolder中加入列表的點(diǎn)擊事件
package com.jelly.imagebrowse.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.jelly.imagebrowse.R;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* 圖片列表適配器
* Created by Jelly on 2016/9/3.
*/
public class ImageRecyclerAdapter extends RecyclerView.Adapter<ImageRecyclerAdapter.ImageHolder>{
private List<String> dataList;
private Context context;
private LayoutInflater inflater;
private OnRecyclerItemClickListener itemClickListener;
public ImageRecyclerAdapter(Context context,List<String> dataList) {
this.context = context;
this.dataList = dataList;
inflater = LayoutInflater.from(context);
}
@Override
public int getItemCount() {
return dataList.size();
}
@Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ImageHolder(inflater.inflate(R.layout.item_image,parent,false),itemClickListener);
}
@Override
public void onBindViewHolder(ImageHolder holder, int position) {
Picasso.with(context).load(dataList.get(position)).resize(200,200).centerCrop().into(holder.image);
}
public void setItemClickListener(OnRecyclerItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public static class ImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView image;
private OnRecyclerItemClickListener itemClickListener;
public ImageHolder(View itemView,OnRecyclerItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
itemView.setOnClickListener(this);
image = (ImageView) itemView.findViewById(R.id.image);
}
@Override
public void onClick(View v) {
if(itemClickListener == null) return;
itemClickListener.click(itemView,getAdapterPosition());
}
}
}
Activity中設(shè)置RecyclerView,加入RecyclerView的點(diǎn)擊事件,進(jìn)入圖片瀏覽的Activity
rv.setLayoutManager(new GridLayoutManager(this,3));
rv.setItemAnimator(new DefaultItemAnimator());
adapter = new ImageRecyclerAdapter(this,images);
adapter.setItemClickListener(new OnRecyclerItemClickListener() {
@Override
public void click(View item, int position) {
ImageBrowseActivity.startActivity(MainActivity.this, (ArrayList<String>) images,position);
}
});
rv.setAdapter(adapter);
顯示效果
圖片瀏覽Activity
在上一Activity上傳入需要顯示的圖片的集合和顯示的Position
public static void startActivity(Context context, ArrayList<String> images, int position){
Intent intent = new Intent(context,ImageBrowseActivity.class);
intent.putStringArrayListExtra("images",images);
intent.putExtra("position",position);
context.startActivity(intent);
}
布局Activity扼劈,顯示圖片的hint和保存按鈕
<?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"
android:background="@android:color/black">
<com.jelly.imagebrowse.view.ViewPagerFixed
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.jelly.imagebrowse.view.ViewPagerFixed>
<TextView
android:id="@+id/hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_margin="10dp"
android:layout_alignParentBottom="true"
android:textColor="@android:color/white"
android:text="0/0"/>
<TextView
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_margin="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:textColor="@android:color/white"
android:text="保存"/>
</RelativeLayout>
在布局文件中使用的ViewPagerFixed锣笨,修復(fù)了在使用PhotoView時的一個Bug
package com.jelly.imagebrowse.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class ViewPagerFixed extends android.support.v4.view.ViewPager {
public ViewPagerFixed(Context context) {
super(context);
}
public ViewPagerFixed(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
try {
return super.onTouchEvent(ev);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
return false;
}
}
ViewPager的Adapter蝌矛,這里使用SparseArray進(jìn)行緩存,PhotoViewAttacher設(shè)置ImageView可以放大縮小 错英,使用Picasso加載圖片入撒,Bitmap.Config.RGB_565提高圖片加載效率,在Picasso的回調(diào)中調(diào)用PhotoViewAttacher的Update刷新走趋,不刷新的話會導(dǎo)致圖片錯位衅金。
package com.jelly.imagebrowse.adapter;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.jelly.imagebrowse.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.List;
import uk.co.senab.photoview.PhotoViewAttacher;
/**
* 圖片瀏覽ViewPageAdapter
* Created by Jelly on 2016/3/10.
*/
public class ViewPageAdapter extends PagerAdapter {
private Context context;
private List<String> images;
private SparseArray<View> cacheView;
private ViewGroup containerTemp;
public ViewPageAdapter(Context context, List<String> images) {
this.context = context;
this.images = images;
cacheView = new SparseArray<>(images.size());
}
@Override
public Object instantiateItem(final ViewGroup container, int position) {
if(containerTemp == null) containerTemp = container;
View view = cacheView.get(position);
if(view == null){
view = LayoutInflater.from(context).inflate(R.layout.vp_item_image,container,false);
view.setTag(position);
final ImageView image = (ImageView) view.findViewById(R.id.image);
final PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher(image);
Picasso.with(context).load(images.get(position)).config(Bitmap.Config.RGB_565).into(image, new Callback() {
@Override
public void onSuccess() {
photoViewAttacher.update();
}
@Override
public void onError() {
}
});
photoViewAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float x, float y) {
Activity activity = (Activity) context;
activity.finish();
}
});
cacheView.put(position,view);
}
container.addView(view);
return view;
}
@Override
public int getCount() {
return images.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
在圖片瀏覽的Activity中獲取需要顯示的圖片和設(shè)置ViewPager的Adapter
//獲取data
Intent intent = view.getDataIntent();
images = intent.getStringArrayListExtra("images");
position = intent.getIntExtra("position",0);
view.setImageBrowse(images,position);
//設(shè)置ViewPager
adapter = new ViewPageAdapter(this,images);
vp.setAdapter(adapter);
vp.setCurrentItem(position);
vp.addOnPageChangeListener(this);
hint.setText(position + 1 + "/" + images.size());
監(jiān)聽ViewPager的滑動事件,設(shè)置hint的顯示
@Override
public void onPageSelected(int position) {
presenter.setPosition(position);
hint.setText(position + 1 + "/" + presenter.getImages().size());
}
加入保存功能
Picasso.with(view.getMyContext()).load(imageUrl).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// 創(chuàng)建目錄
File appDir = new File(Environment.getExternalStorageDirectory(), "JellyImage");
if (!appDir.exists()) {
appDir.mkdir();
}
String imageType = getImageType(imageUrl); //獲取圖片類型
String fileName = System.currentTimeMillis() + "." + imageType;
File file = new File(appDir, fileName);
//保存圖片
try {
FileOutputStream fos = new FileOutputStream(file);
if(TextUtils.equals(imageType,"jpg")) imageType = "jpeg";
imageType = imageType.toUpperCase();
bitmap.compress(Bitmap.CompressFormat.valueOf(imageType), 100, fos);
fos.flush();
fos.close();
Toast.makeText(view.getMyContext(),"保存成功",Toast.LENGTH_SHORT).show(); //Toast
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系統(tǒng)圖庫
try {
MediaStore.Images.Media.insertImage(view.getMyContext().getContentResolver(), file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知圖庫更新
view.getMyContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
到這里圖片瀏覽器的功能就實(shí)現(xiàn)簿煌,效果圖:
完整代碼:Mango