美文网首页
Android PhotoPicker 自定义图片选择器

Android PhotoPicker 自定义图片选择器

作者: 小熊_c37d | 来源:发表于2017-08-14 14:05 被阅读0次
    我们来先看效果图
    Paste_Image.png 20170814133628.gif
    概述

    关于手机图片加载器,在当今像素随随便便破千万的时代,一张图片占据的内存都相当可观,作为高大尚程序猿的我们,有必要掌握图片的压缩,缓存等处理,以到达纵使你有万张照片,纵使你的像素再高,我们也能正确的显示所有的图片。

    简单描述一下

    1.显示手机上所有的图片
    2.选中时候图片变暗。
    3.可多选

    实现
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
      compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
      compile 'com.github.bumptech.glide:glide:3.6.1'
    

    这里我们没有写6.0获取权限 自行代码获取

    1.既然我们需要显示手机上的所有图片,那么我们首先就需要拿到手机上的所有图片地址,当然这个过程在子线程理的,当 获取完成后通过handler发送完成消息

    private void getImages() {
    
        new Thread(new Runnable() {
            @Override
            public void run() {
                fileNames = new ArrayList();
                Cursor cursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
                if (cursor == null) {
                    Log.i(TAG, "run: 空");
                    return;
                }
                while (cursor.moveToNext()) {
                    //获取图片的地址
                    byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    fileNames.add(new String(data, 0, data.length - 1));
                    Log.i(TAG, "run: " + new String(data, 0, data.length - 1));
                }
                mHandler.sendMessage(mHandler.obtainMessage());
                cursor.close();
            }
        }).start();
    }
    
    
    
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG, "handleMessage: 完成");
            mRv.setAdapter(mPhotoPickerAdapter = new PhotoPickerAdapter(fileNames));
        }
    };
    

    2.这个时候我们已经有了所有图片的地址接下来我们需要显示图片了,我们看到效果,每行有3个,并且条目之间是有间距的,我这里使用的是RecyclerView,

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        mRv = findViewById(R.id.rv);
        mRv.setLayoutManager(new GridLayoutManager(this, 3));
        mRv.addItemDecoration(new SpaceItemDecoration(5));
        getImages();
    }
    
    
    
    
    
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private  int  space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
      /**这里定义的间距*/
        @Override
     public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            outRect.top = space;
        }
    }
    

    3.这个时候我们RecyclerView 基本配置配置完成。接下来我们看下adapter,从下列代码我们可以看到,我这里直接采用的是谷歌推荐的图片加载Glide加载图片的,图片选中的时候调用setAlpha 设置透明度。
    这里提供了一个getImages 方法。 取到所有的已经选中图片的地址;

    public class PhotoPickerAdapter extends RecyclerView.Adapter<PhotoPickerAdapter.MyViewHolder> {
        private ArrayList<String> images;
        private ArrayList<Boolean> cb;
        private Context mContext;
        public PhotoPickerAdapter(ArrayList<String> images){
            this.images=images;
            cb=new ArrayList<>();
            for (int i = 0; i < images.size(); i++) {
                cb.add(false);
            }
        }
    
        public ArrayList<String> getImages(){
            ArrayList<String> strings =new ArrayList<>();
            for (int i = 0; i < cb.size(); i++) {
                if(cb.get(i)){
                    strings.add(images.get(i));
                }
            }
            return strings;
        }
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mContext=parent.getContext();
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    mContext).inflate(R.layout.photo_item, parent,
                    false));
            return holder;
        }
    
        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            Glide.with(mContext)
                    .load(images.get(position))
                    .crossFade()
                    .into(holder.iv);
    
            holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    cb.set(position,b);
                    holder.iv.setAlpha(cb.get(position)==true?0.5f:1f);
                }
            });
            holder.cb.setChecked(cb.get(position));
            holder.iv.setAlpha(cb.get(position)==true?0.5f:1f);
    
        }
    
        @Override
        public int getItemCount() {
            return images.size();
        }
    
        public class MyViewHolder extends RecyclerView.ViewHolder{
            public ImageView iv;
            public CheckBox cb;
            public MyViewHolder(View itemView) {
                super(itemView);
                iv=itemView.findViewById(R.id.iv);
                cb=itemView.findViewById(R.id.cb);
            }
    
        }
    
    }
    
    完整代码

    PhotoPickerActivity

    public class PhotoPickerActivity extends Activity implements View.OnClickListener {
        private static final String TAG = "PhotoPickerActivity";
        private ArrayList<String> fileNames;
        private PhotoPickerAdapter mPhotoPickerAdapter;
        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.i(TAG, "handleMessage: 完成");
                mRv.setAdapter(mPhotoPickerAdapter = new PhotoPickerAdapter(fileNames));
            }
        };
        private RecyclerView mRv;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_photo);
            mRv = findViewById(R.id.rv);
            mRv.setLayoutManager(new GridLayoutManager(this, 3));
            mRv.addItemDecoration(new SpaceItemDecoration(5));
            getImages();
        }
    
    
        private void getImages() {
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    fileNames = new ArrayList();
                    Cursor cursor = getContentResolver().query(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
                    if (cursor == null) {
                        Log.i(TAG, "run: 空");
                        return;
                    }
                    while (cursor.moveToNext()) {
                        //获取图片的地址
                        byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        fileNames.add(new String(data, 0, data.length - 1));
                        Log.i(TAG, "run: " + new String(data, 0, data.length - 1));
                    }
                    mHandler.sendMessage(mHandler.obtainMessage());
                    cursor.close();
                }
            }).start();
        }
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.confirm:
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("选中的图片"+"\r\n");
                    ArrayList<String> arrayList = mPhotoPickerAdapter.getImages();
                    for (int i = 0; i < arrayList.size(); i++) {
                        String  s=arrayList.get(i);
                        String[]  strs=  s.split("/");
                        stringBuffer.append(strs[strs.length-1]+"\r\n");
                    }
                    Toast.makeText(PhotoPickerActivity.this,stringBuffer.toString(),Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    

    activity_photo

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
    
    
        <android.support.v7.widget.RecyclerView
            android:layout_weight="1"
            android:background="#272727"
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v7.widget.RecyclerView>
    
        <RelativeLayout
            android:background="@android:color/white"
            android:layout_width="match_parent"
            android:layout_height="40dp">
            <TextView
                android:onClick="onClick"
                android:id="@+id/confirm"
                android:background="#0094ff"
                android:layout_alignParentRight="true"
                android:layout_margin="5dp"
                android:text="确定"
                android:textColor="#844200"
                android:gravity="center"
                android:textSize="14sp"
                android:layout_width="60dp"
                android:layout_height="match_parent"/>
        </RelativeLayout>
    </LinearLayout>
    

    SpaceItemDecoration

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private  int  space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
    
            // Add top margin only for the first item to avoid double space between items
           // if(parent.getChildPosition(view) != 0)
                outRect.top = space;
        }
    }
    

    PhotoPickerAdapter

    public class PhotoPickerAdapter extends RecyclerView.Adapter<PhotoPickerAdapter.MyViewHolder> {
        private ArrayList<String> images;
        private ArrayList<Boolean> cb;
        private Context mContext;
        public PhotoPickerAdapter(ArrayList<String> images){
            this.images=images;
            cb=new ArrayList<>();
            for (int i = 0; i < images.size(); i++) {
                cb.add(false);
            }
        }
    
        public ArrayList<String> getImages(){
            ArrayList<String> strings =new ArrayList<>();
            for (int i = 0; i < cb.size(); i++) {
                if(cb.get(i)){
                    strings.add(images.get(i));
                }
            }
            return strings;
        }
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mContext=parent.getContext();
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    mContext).inflate(R.layout.photo_item, parent,
                    false));
            return holder;
        }
    
        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            Glide.with(mContext)
                    .load(images.get(position))
                    .crossFade()
                    .into(holder.iv);
    
            holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    cb.set(position,b);
                    holder.iv.setAlpha(cb.get(position)==true?0.5f:1f);
                }
            });
            holder.cb.setChecked(cb.get(position));
            holder.iv.setAlpha(cb.get(position)==true?0.5f:1f);
    
        }
    
        @Override
        public int getItemCount() {
            return images.size();
        }
    
        public class MyViewHolder extends RecyclerView.ViewHolder{
            public ImageView iv;
            public CheckBox cb;
            public MyViewHolder(View itemView) {
                super(itemView);
                iv=itemView.findViewById(R.id.iv);
                cb=itemView.findViewById(R.id.cb);
            }
    
        }
    
    }
    

    photo_item

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:descendantFocusability="blocksDescendants"
                  android:layout_width="match_parent"
                  android:layout_height="120dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:scaleType="centerCrop"
                android:id="@+id/iv"
                android:layout_width="match_parent"
                android:layout_height="120dp"/>
            <CheckBox
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"
                android:id="@+id/cb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </RelativeLayout>
    
    </LinearLayout>

    相关文章

      网友评论

          本文标题:Android PhotoPicker 自定义图片选择器

          本文链接:https://www.haomeiwen.com/subject/zulurxtx.html