android 拍照显示多张图片(网格布局)

效果图
android 拍照显示多张图片(网格布局)_第1张图片

Activity的代码,里面包含拍照,以及拍照返回的处理(目标版本是7.0的拍照代码不适用)

package com.hjqjl.mulitimageselect;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.hjqjl.mulitimageselect.adapter.ImageAdapter;
import com.hjqjl.mulitimageselect.util.BitmapUtils;
import com.hjqjl.mulitimageselect.util.FileUtils;
import com.orhanobut.logger.Logger;

import java.io.File;

public class ImageSelectActivity extends AppCompatActivity {
    //临时目录
    public static final String mSaveTemporaryPath = Environment.getExternalStorageDirectory() + "/" + BuildConfig.APPLICATION_ID + "/temporary/";
    private final int PHOTO_CAMERA_REQUEST_CODE = 2003;

    private ImageAdapter imageAdapter = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                /*拍照返回*/
                case PHOTO_CAMERA_REQUEST_CODE:
                    Logger.v("-----onActivityResult:" + imgFile.getAbsolutePath());

                    File fileDir = new File(mSaveTemporaryPath);
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                    File compressFile = FileUtils.createImageFile(fileDir);//创建临时文件,覆盖原来的File文件的时候,不知道问什么有时名字会自动加上时间戳
                    if (compressFile != null) {
                        BitmapUtils.compressPicture(imgFile.getAbsolutePath(), compressFile);

                        Logger.v("" + compressFile.getAbsolutePath());

                        //将照片文件放入集合中
                        imageAdapter.getDataList().add(compressFile);
                        imageAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(this, "获取图片失败,请重新上传", Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_select);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_selectImage_image);
        Button button = (Button) findViewById(R.id.btn_selectImage_button);

        imageAdapter = new ImageAdapter(this);
        recyclerView.setAdapter(imageAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(ImageSelectActivity.this, 3));

        imageAdapter.setOnPicClickListener(new ImageAdapter.OnPicClickListener() {
            @Override
            public void onPicClick() {
                openCamera();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ImageSelectActivity.this, "我只是个按钮", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private File imgFile;

    /**
     * 拍照
     */
    private void openCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(mSaveTemporaryPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        imgFile = new File(mSaveTemporaryPath, "photo.jpg");
        Uri mUri = Uri.fromFile(imgFile);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        cameraIntent.putExtra("return-data", true);
        startActivityForResult(cameraIntent, PHOTO_CAMERA_REQUEST_CODE);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭界面的时候删除文件
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (File file : imageAdapter.getDataList()) {
                    FileUtils.deleteFolderFile(file);
                }
                FileUtils.deleteFolderFile(imgFile);
            }
        }).start();
    }
}

布局文件




    

        

            
        
    

    

展示图片的网格布局的adapter如下:

package com.hjqjl.mulitimageselect.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 android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hjqjl.mulitimageselect.R;

import java.io.File;

public class ImageAdapter extends ListBaseAdapter {
    private LayoutInflater mLayoutInflater;

    // 图片的点击事件
    public interface OnPicClickListener {
        void onPicClick();
    }

    private OnPicClickListener mOnPicClickListener;

    public void setOnPicClickListener(OnPicClickListener mOnPicClickListener) {
        this.mOnPicClickListener = mOnPicClickListener;
    }

    public ImageAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
        mContext = context;
    }

    @Override
    public int getItemCount() {
        return mDataList.size() + 1;//比集合里的数据多一条,显示自定义的添加图片按钮
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(mLayoutInflater.inflate(R.layout.item_image_seclect, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        final int mPosition = viewHolder.getAdapterPosition();
        if (mPosition == getItemCount() - 1) {//数据的最后一条(显示的添加图片的那个按钮)
            viewHolder.ivPic.setBackgroundResource(R.mipmap.bg_take_photo);
            if (mOnPicClickListener != null) {
                viewHolder.ivPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnPicClickListener.onPicClick();
                    }
                });
            }
        } else {
            File fileImage = mDataList.get(mPosition);
            viewHolder.ivPic.setBackgroundResource(R.mipmap.bg_take_photo);
            Glide.with(mContext).load(fileImage).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(viewHolder.ivPic);
            viewHolder.ivPic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "点击的图片", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView ivPic;

        ViewHolder(View itemView) {
            super(itemView);
            ivPic = (ImageView) itemView.findViewById(R.id.iv_imageSelect_item_img);
        }
    }
}

ImageAdapter 继承的父类ListBaseAdapter是自定义的,将一些常用的方法提取出来了。代码如下:

package com.hjqjl.mulitimageselect.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * RecyclerView的adapter的辅助类,继承本类使用
 *
 * @param 
 */
public class ListBaseAdapter extends RecyclerView.Adapter {
    protected Context mContext;

    protected ArrayList mDataList = new ArrayList<>();

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public List getDataList() {
        return mDataList;
    }

    public void setDataList(Collection list) {
        this.mDataList.clear();
        this.mDataList.addAll(list);
        notifyDataSetChanged();
    }

    public void addAll(Collection list) {
        int lastIndex = this.mDataList.size();
        if (this.mDataList.addAll(list)) {
            notifyItemRangeInserted(lastIndex, list.size());
        }
    }

    public void remove(int position) {
        if (this.mDataList.size() > 0) {
            mDataList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        mDataList.clear();
        notifyDataSetChanged();
    }
}

ImageAdapter的item布局文件:




    


完毕。 demo:https://gitee.com/hjqjl/MulitImageSelect

转载于:https://my.oschina.net/u/1270204/blog/848677

你可能感兴趣的:(android 拍照显示多张图片(网格布局))