Android简单的多图选择器

来源:互联网 发布:2017中国城市癌症数据 编辑:程序博客网 时间:2024/04/29 22:21

我们知道实现一张图片的选择,一般直接调用系统选择即可,返回的信息,存在与uri中,但是只要我们将这个uri改一次,就会得到所有图片的集合。

Cursor cursor= MediaStore.Images.Media.query(getContentResolver(),                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,path,                null,null,null);

拿到所有的图片后将其显示在一个列表中即可。

 @ViewInject(R.id.recyclerview)    private RecyclerView recyclerView;    private List<String> paths;    private LruCache<String,Bitmap> cache;    @ViewInject(R.id.tv_count)    private TextView tvSelectCount;    private List<String> resultPaths;    @ViewInject(R.id.btn_submit)    private FloatingActionButton btnStnSubmit;    private int size;    private String root;    @Override    protected int initLayout() {        return R.layout.activity_muti_image_select;    }    @Override    protected void initView() {        initCache();        paths=initPath();        size=getIntent().getIntExtra("size",-1);        root= Environment.getExternalStorageDirectory().getAbsolutePath()+"/image/cache/";    }    @Override    protected void initData() {        StaggeredGridLayoutManager manager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);        recyclerView.setLayoutManager(manager);        MyAdapter adapter=new MyAdapter();        recyclerView.setAdapter(adapter);        resultPaths=new ArrayList<>();        btnStnSubmit.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent=new Intent();                intent.putStringArrayListExtra("data", (ArrayList<String>) resultPaths);                setResult(RESULT_OK,intent);                finish();            }        });    }    private List<String> initPath(){        List<String> paths=new ArrayList<>();        String []path=new String[]{MediaStore.Images.Media.DATA};        Cursor cursor= MediaStore.Images.Media.query(getContentResolver(),                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,path,                null,null,null);        while (cursor.moveToNext()) {            int index = cursor.getColumnIndex(path[0]);            String readPath = cursor.getString(index);            paths.add(readPath);        }        return paths;    }    private class MyAdapter extends RecyclerView.Adapter<ViewHolder>{        @Override        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {            return new ViewHolder( LayoutInflater.from(MutiImageSelectActivity.this).inflate(R.layout.muti_image_grid_layout,null));        }        @Override        public void onBindViewHolder(ViewHolder holder, final int position) {            FrameLayout.LayoutParams imageParams= (FrameLayout.LayoutParams) holder.imageView.getLayoutParams();            imageParams.width=CommonUtils.getScreenWidth(MutiImageSelectActivity.this)/3;            imageParams.height=CommonUtils.getScreenWidth(MutiImageSelectActivity.this)/3;            holder.imageView.setLayoutParams(imageParams);            if (cache.get(String.valueOf(position))!=null){                holder.imageView.setImageBitmap(cache.get(String.valueOf(position)));            }else {                holder.imageView.setImageDrawable(getResources().getDrawable(R.mipmap.ic_error));                BitmapTask task=new BitmapTask(holder,position);                task.execute(paths.get(position),null,null);            }            holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {                @Override                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                    int currentCountIndex=tvSelectCount.getText().toString().indexOf("选");                    int currentCount=Integer.parseInt(tvSelectCount.getText().toString().substring(currentCountIndex+1,currentCountIndex+2));                    if (isChecked){                        if (size!=-1){                            if (resultPaths.size()==1){                                CommonUtils.toast(mContext,"只能修改一张图片");                                return;                            }                        }else {                            if (resultPaths.size()==5){                                CommonUtils.toast(mContext,"最多上传5张图片");                                return;                            }                        }                        tvSelectCount.setText("已选"+(++currentCount)+"张");                        resultPaths.add(paths.get(position));                    }else {                        tvSelectCount.setText("已选"+(--currentCount)+"张");                        resultPaths.remove(paths.get(position));                    }                }            });        }        @Override        public long getItemId(int position) {            return position ;        }        @Override        public int getItemCount() {            return paths.size();        }    }    private class ViewHolder extends RecyclerView.ViewHolder{        ImageView imageView;        CheckBox checkBox;        public ViewHolder(View itemView) {            super(itemView);            checkBox= (CheckBox) itemView.findViewById(R.id.checkbox);            imageView= (ImageView) (itemView).findViewById(R.id.image);        }    }    private void initCache(){        int maxMemory= (int) (Runtime.getRuntime().maxMemory()/8);        cache=new LruCache<String, Bitmap>(maxMemory){            @Override            protected int sizeOf(String key, Bitmap value) {                return value.getRowBytes()*value.getHeight();            }        };    }    private class BitmapTask extends AsyncTask<String,String,Bitmap>{        private ViewHolder viewHolder;        private int pos;        public BitmapTask(ViewHolder viewHolder,int pos){            super();            this.viewHolder=viewHolder;            this.pos=pos;        }        @Override        protected Bitmap doInBackground(String... params) {            try {                int index=paths.get(pos).lastIndexOf("/");                String key=paths.get(pos).substring(index+1);                if (BitmapFactory.decodeFile(root+key)!=null){                 cache.put(String.valueOf(pos),BitmapFactory.decodeFile(root+key));                    return BitmapFactory.decodeFile(root+key);                }                Bitmap bitmap=CommonUtils.compressFromFile(paths.get(pos),                        CommonUtils.getScreenWidth(MutiImageSelectActivity.this)/3, CommonUtils.getScreenWidth(MutiImageSelectActivity.this)/3);                saveFile(bitmap,key);                cache.put(String.valueOf(pos),bitmap);                return bitmap;            } catch (FileNotFoundException e) {                e.printStackTrace();            }            return null;        }        @Override        protected void onPostExecute(Bitmap bitmap) {            viewHolder.imageView.setImageBitmap(bitmap);        }    }    private  void saveFile(Bitmap bitmap,String key) throws FileNotFoundException{        File file=new File(root);        if (!file.exists()){            file.mkdirs();        }        String fileName=root+key;        FileOutputStream fos=new FileOutputStream(fileName);        bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);    }

也不知道什么原因,这个压缩图片貌似很耗时,倒是进图的时候是空白。
所以我就把他放进了子线程。同时使用lrcache作为其1级缓存。文件作为二级缓存。上面的 checkbox会实现图片的选择与否。并将其路径以集合的形式返回.

0 0
原创粉丝点击