Android图片选择器
本文是我的第二篇博客,如果有错误的地方,希望大家多多指点,相信大家都知道网上有很多第三方的图片选择器,但是在真正的项目中却遇到例如一个很重要的问题,定制属于自己的图品选择器,很多第三方的无法满足我们的这一需求,因此我自己写了一个,代码简单,我在下面附带了源码,刚兴趣的朋友可以下载了自己修改. 本项目没有依赖人任何第三方的类库,主要设计思路就是:一个图片加载类(单例)+利用ContentProvider扫描手机的图片+GridView显示图片 本篇博客的主要内容是仿微信图片选择器,主要步骤有如下几点
① 图片加载类(单例)
② 获取手机本地图片
③ 可以设置图片选择个数
下面是在是真机上的效果预览:
本项目的主要功能:
① 默认显示图片最多的文件夹图片,以及底部显示图片总数量;
② 点击底部,弹出popupWindow,popupWindow包含所有含有图片的文件夹,以及显示每个文件夹中图片数量;注:此时Activity变暗
③ 选择任何文件夹,进入该文件夹图片显示,可以点击选择图片,当然了,点击已选择的图片则会取消选择;注:选中图片变暗 当然了,最重要的效果一定流畅,不能动不动OOM~~ 本人测试手机乐视1s,图片3802张,和小米红米,小米2s,未出现OOM异常,效果也是非常流畅, 不过存在bug在所难免,大家可以留言说下自己发现的bug;文末会提供源码下载。
下面是对项目的一一讲解:
第一步:核心方法:图片加载工具类 ImageLoader:本项目的图片加载采用Google的Gilde,Glide是一个强大的资源加载工具类,支持视频、图片、GIF等多种格式的资源,功能强大,不知道的同学可以去网上搜一搜。具体的用法在这里也不做赘述。
第二步:主界面设计:
主界面布局,主布局的设计思路是,用GridView布局显示图片,并为GridView编写响应的适配器.
第三步:获取手机上的全部图片:
该方法会扫描手机上的所有图片信息,并显示到主界面上,扫描结束,得到一个所有包含图片的文件夹信息的List;
对于文件夹信息,我们单独创建了一个FolderBean:
扫描说及图片的方法
/**
* 利用ContentProvider扫描手机的图片
*/
private void initDatas() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(context, "当前存储卡不可用", Toast.LENGTH_SHORT).show();
return;
}
mProgress = ProgressDialog.show(context, null, "正在加载...");
new Thread() {
@Override
public void run() {
FolderBean folderBean1 = new FolderBean();
folderBean1.setCount(0);
folderBean1.setName("所有图片");
folderBean1.setDir("/所有图片");
folderBean1.setFirstImgPath("/所有图片");
mFolderBeans.add(folderBean1);
Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = context.getContentResolver();
// 获取手机上的所有的图片
Cursor cursor = cr.query(mImgUri, null,
MediaStore.Images.Media.MIME_TYPE + " = ? or " + MediaStore.Images.Media.MIME_TYPE + " = ? ",
new String[] { "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED);
Log.e("图片选择器", "4");
Set mDirPaths = new HashSet();
Log.e("图片选择器", "5");
while (cursor.moveToNext()) {
final String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
File parentFile = new File(path).getParentFile();
if (parentFile == null) {
continue;
}
String dirPath = parentFile.getAbsolutePath();
FolderBean folderBean = null;
if (mDirPaths.contains(dirPath)) {
continue;
} else {
mDirPaths.add(dirPath);
folderBean = new FolderBean();
folderBean.setDir(dirPath);
folderBean.setFirstImgPath(path);
}
if (parentFile.list() == null)
continue;
int picSize = parentFile.list(new FilenameFilter() {
//对文件进行过滤,获取图片文件
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
return true;
}
return false;
}
}).length;
folderBean.setCount(picSize);
mFolderBeans.add(folderBean);
if (picSize > mMaxCount) {
mMaxCount = picSize;
mCurrentDir = parentFile;
}
}
Log.e("图片选择器", "6");
cursor.close();
// 通知handler扫描完成
mHandler.sendEmptyMessage(DATA_LOADED);
}
}.start();
}
FolderBean
public class FolderBean {
private String dir;
private String name;
private String firstImgPath;
private int count;
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
int lastIndexOf = this.dir.lastIndexOf("/") + 1;
this.name = this.dir.substring(lastIndexOf);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstImgPath() {
return firstImgPath;
}
public void setFirstImgPath(String firstImgPath) {
this.firstImgPath = firstImgPath;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return dir;
}
}
第四步:把图片信息显示到布局:
public class ImageAdapter extends BaseAdapter {
private static Set mSelectImg = new HashSet();
private Context context;
private List mImgPahts;
private String mDirPath;
private LayoutInflater mInflater;
private Handler handler;
public ImageAdapter(Context context, List mDatas, String dirPath, Handler handler) {
this.context = context;
this.mImgPahts = mDatas;
this.mDirPath = dirPath;
mInflater = LayoutInflater.from(context);
this.handler = handler;
}
@Override
public int getCount() {
return mImgPahts.size();
}
@Override
public Object getItem(int position) {
return mImgPahts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_griadview, null);
viewHolder = new ViewHolder();
viewHolder.mImg = (ImageView) convertView.findViewById(R.id.id_item_image);
viewHolder.mSelect = (ImageButton) convertView.findViewById(R.id.id_item_select);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (mImgPahts.get(position).equals("null###")) {
viewHolder.mImg.setImageResource(R.drawable.photograph_icon);
viewHolder.mImg.setScaleType(ScaleType.CENTER);
viewHolder.mSelect.setVisibility(View.GONE);
viewHolder.mImg.setColorFilter(null);
viewHolder.mImg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.sendEmptyMessage(4);
}
});
} else {
viewHolder.mImg.setImageResource(R.drawable.not_loaded_icon);
viewHolder.mImg.setScaleType(ScaleType.FIT_XY);
viewHolder.mSelect.setVisibility(View.VISIBLE);
viewHolder.mSelect.setImageResource(R.drawable.login_chexbox);
viewHolder.mImg.setColorFilter(null);
if (mDirPath.equals("")) {
ImageLoader.getInstance(3, com.awang.imageloader.util.ImageLoader.Type.FIFO)
.LoadImage(mImgPahts.get(position), viewHolder.mImg);
} else {
ImageLoader.getInstance(3, com.awang.imageloader.util.ImageLoader.Type.FIFO)
.LoadImage(mDirPath + "/" + mImgPahts.get(position), viewHolder.mImg);
}
final String filePath = mDirPath.equals("") ? mImgPahts.get(position)
: mDirPath + "/" + mImgPahts.get(position);
viewHolder.mImg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImgaeSelectActivity.getCount();
if (ImgaeSelectActivity.contains(filePath)) {
ImgaeSelectActivity.removeSelectImg(filePath);
handler.sendEmptyMessage(2);
viewHolder.mSelect.setImageResource(R.drawable.login_chexbox);
viewHolder.mImg.setColorFilter(null);
} else {
if (ImgaeSelectActivity.getCount() >= 3) {
handler.sendEmptyMessage(1);
} else {
ImgaeSelectActivity.addSelectImg(filePath);
handler.sendEmptyMessage(1);
viewHolder.mSelect.setImageResource(R.drawable.login_chexbox_s);
viewHolder.mImg.setColorFilter(Color.parseColor("#77000000"));
}
}
// notifyDataSetChanged();
}
});
if (ImgaeSelectActivity.contains(filePath)) {
viewHolder.mSelect.setImageResource(R.drawable.login_chexbox_s);
viewHolder.mImg.setColorFilter(Color.parseColor("#77000000"));
}
}
return convertView;
}
public class ViewHolder {
ImageView mImg;
ImageButton mSelect;
}
}
第五步:展现文件夹的PopupWindow:
要实现的效果是,点击底部的布局弹出我们的文件夹选择框,并且我们弹出框后面的Activity要变暗;
public class ListImageDirPopupWindow extends PopupWindow {
private int width;
private int heightl;
private View mContentView;
private ListView mListView;
private List mDatas;
private ListDirAdapter mAdapter;
public interface setOnDirSelectListerener {
void onSelected(FolderBean folderBean, int position);
}
private static int currentSelect = 0;
public setOnDirSelectListerener dirSelectListerener;
public ListImageDirPopupWindow(Context context, List mDatas) {
calWidthAndHeight(context);
mContentView = LayoutInflater.from(context).inflate(R.layout.popuwid, null);
this.mDatas = mDatas;
setContentView(mContentView);
setWidth(width);
setHeight(heightl);
setFocusable(true);
setTouchable(true);
setOutsideTouchable(true);
setBackgroundDrawable(new BitmapDrawable());
setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
dismiss();
return true;
}
return false;
}
});
initViews(context);
initEvent();
}
private void initViews(Context context) {
mListView = (ListView) mContentView.findViewById(R.id.id_list_dir);
mAdapter = new ListDirAdapter(context, mDatas);
mListView.setAdapter(mAdapter);
}
public void initEvent() {
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
if (dirSelectListerener != null) {
dirSelectListerener.onSelected(mDatas.get(position), position);
currentSelect = position;
mAdapter.notifyDataSetChanged();
}
}
});
}
public void setDirSelectListerener(setOnDirSelectListerener dirSelectListerener) {
this.dirSelectListerener = dirSelectListerener;
}
/**
* 计算popupWindow的宽度和高度
*/
private void calWidthAndHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
width = outMetrics.widthPixels;
heightl = (int) (outMetrics.heightPixels * 0.7);
}
private class ListDirAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private List mDatas;
public ListDirAdapter(Context context, List mDatas) {
super(context, 0, mDatas);
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_popuwid, parent, false);
viewHolder.mImg = (ImageView) convertView.findViewById(R.id.id_dir_item_image);
viewHolder.setSel = (ImageView) convertView.findViewById(R.id.set_sel);
viewHolder.mDirName = (TextView) convertView.findViewById(R.id.id_dir_item_name);
viewHolder.mDirCount = (TextView) convertView.findViewById(R.id.id_dir_item_count);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
FolderBean bean = getItem(position);
// 重置
viewHolder.mImg.setImageResource(R.drawable.not_loaded_icon);
ImageLoader.getInstance().LoadImage(bean.getFirstImgPath(), viewHolder.mImg);
viewHolder.mDirName.setText(bean.getName());
if (bean.getCount() == 0) {
viewHolder.mDirCount.setText("");
} else {
viewHolder.mDirCount.setText("" + bean.getCount());
}
if (position == currentSelect) {
viewHolder.setSel.setVisibility(View.VISIBLE);
} else {
viewHolder.setSel.setVisibility(View.GONE);
}
return convertView;
}
private class ViewHolder {
ImageView setSel;
ImageView mImg;
TextView mDirName;
TextView mDirCount;
}
}
public static void setCurrent(int position){
}
}
布局:
主要的代码就这么多,
总结:本项目的主要代码基本已经贴出来了,感兴趣的朋友也可以去下载本人的项目,下载地址也已经贴了出来,最后,如有不对的地方,请多多指教.
项目下载地址:
http://download.csdn.net/download/waa_0618/9748835
[1]: http://math.stackexchange.com/
[2]: https://github.com/jmcmanus/pagedown-extra "Pagedown Extra"
[3]: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
[4]: http://bramp.github.io/js-sequence-diagrams/
[5]: http://adrai.github.io/flowchart.js/
[6]: https://github.com/benweet/stackedit