图片选择器(支持相册和相机),只需一步实现

写了一段时间的代码,发现老是做些重复的工作,效率低。其实很多是可以优化封装成库,下次使用时,能快速集成,减少开发时间。
图片选择器是很多app都用到的,我给他封装了一下,只需一步。

只要继承BaseCameraActivity,设置下监听器就好了

public class MainActivity extends BaseCameraActivity implements BaseCameraActivity.OnSelectPhotoInterface {
    @Bind(R.id.imageview)
    public ImageView mIndexIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setOnSelectPhotoListener(this);
    }

    @OnClick(R.id.gallery_select_btn)
    public void clickGallerySelect(){
//        startChoosePhotoByDialogMode();
        startChoosePhotoByInlineMode();
    }

    @Override
    public void onCropImageCancel() {
    }

    @Override
    public void onCropImageDone(String imagePath) {
        Bitmap bitmap = BitmapUtils.getBitmapAutoResize(imagePath, this);
        if(bitmap != null){
            mIndexIv.setImageBitmap(bitmap);
        }
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }
}

这是主activity,就这么简单。

BaseCameraActivity

public class BaseCameraActivity extends Activity {
    public final static String SDPATH = Environment.getExternalStorageDirectory() + "/";
    private static final int CODE_RESULT_OPEN_CAMERA = 100;
    private static final int CODE_RESULT_OPEN_GALLERY = 101;
    private static final int CODE_RESULT_CROP_IMAGE = 102;

    public final static String SDPATH_APP_ROOT = SDPATH + "weread";
    public static final String INTENT_KEY_IMAGE_PATH = "intent_key_image_path";
    public static final String INTENT_KEY_CROPED_IMAGE_PATH = "intent_key_croped_image_path";

    private String mPhotoImagePath;

    private void openCamera() {
        DebugTools.d("photo2 openCamera");
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(SDPATH_APP_ROOT);
            if(!dir.exists()){
                dir.mkdirs();
            }

            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            File file = new File(dir, String.valueOf(System.currentTimeMillis())+ ".jpg");
            Uri imageUri = Uri.fromFile(file);
            mPhotoImagePath = file.getAbsolutePath();

            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            openCameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);

            startActivityForResult(openCameraIntent, CODE_RESULT_OPEN_CAMERA);
        } else {
            Toast.makeText(this, "没有储存卡", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        DebugTools.d("photo2 onActivityResult");
        switch (requestCode) {
            case CODE_RESULT_OPEN_CAMERA:
                handleActivityResultByOpenCamera();
                break;
            case CODE_RESULT_CROP_IMAGE:
                handleActivityResultByCropImage(data);
                break;

            case CODE_RESULT_OPEN_GALLERY:
                handleActivityResultByGallery(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleActivityResultByOpenCamera(){
        boolean isCancel = isCancelPhoto();
        DebugTools.d("photo2 photo and come back, isCancel: " + isCancel);
        if(!isCancel){
            onPhotoImageDone(mPhotoImagePath);
        }else{
            onPhotoImageCancel();
        }
    }

    private void handleActivityResultByGallery(Intent data){
        if(data == null){
            return;
        }
        String path = data.getStringExtra(INTENT_KEY_IMAGE_PATH);
        if(TextUtils.isEmpty(path)){
            openCamera();
        }else{
            onPhotoImageDone(path);
        }
    }

    private void handleActivityResultByCropImage(Intent data){
        if(data == null){
            return;
        }

        String path = data.getStringExtra(INTENT_KEY_CROPED_IMAGE_PATH);
        if(TextUtils.isEmpty(path)){
            if(mOnSelectPhotoListener != null){
                mOnSelectPhotoListener.onCropImageCancel();
            }
        }else{
            if(mOnSelectPhotoListener != null){
                mOnSelectPhotoListener.onCropImageDone(path);
            }
        }
    }

    private boolean isCancelPhoto(){
        return !CommonTools.isFileExist(mPhotoImagePath);
    }

    private void onPhotoImageDone(String imagePath){
        DebugTools.d("photo2 onPhotoImageDone imagePath: " + imagePath);
        if(TextUtils.isEmpty(imagePath)){
            return;
        }
        jump2CropImageActivity(imagePath);
    }

    private void onPhotoImageCancel(){
        DebugTools.d("photo2 onPhotoImageCancel");
    }

    private void jump2CropImageActivity(String imagePath){
        DebugTools.d("photo2 jump2CropImageActivity imagePath: " + imagePath);
        Intent intent = new Intent(this, CropImageActivity.class);
        intent.putExtra(INTENT_KEY_IMAGE_PATH, imagePath);
        startActivityForResult(intent, CODE_RESULT_CROP_IMAGE);
    }

    protected void startChoosePhotoByDialogMode(){
        showCameraGalleryDialog();
    }

    protected void startChoosePhotoByInlineMode(){
        jump2SelectPhotoPage(false);
    }

    private SelectCameraGalleryDialog mDialog;
    private void showCameraGalleryDialog(){
        if(mDialog == null){
            mDialog = new SelectCameraGalleryDialog(this);
        }
        setDialogListener(mDialog);
        if(!mDialog.isShowing()){
            mDialog.show();
        }
    }

    private void setDialogListener(SelectCameraGalleryDialog dialog){
        dialog.setOnSelectCameraGalleryListener(new SelectCameraGalleryDialog.OnSelectCameraGalleryListener() {
            @Override
            public void onSelectCameraGallery(boolean isCamera) {
                if (isCamera) {
                    openCamera();
                } else {
                    jump2SelectPhotoPage(true);
                }
            }
        });
    }

    private void jump2SelectPhotoPage(boolean isDialogMode){
        Intent intent = new Intent(this, SelectPhotoActivity.class);
        intent.putExtra(SelectPhotoActivity.KEY_IS_DIALOG_MODE, isDialogMode);
        startActivityForResult(intent, CODE_RESULT_OPEN_GALLERY);
    }

    private OnSelectPhotoInterface mOnSelectPhotoListener;
    public void setOnSelectPhotoListener(OnSelectPhotoInterface listener){
        mOnSelectPhotoListener = listener;
    }
    public interface OnSelectPhotoInterface{
        public void onCropImageCancel();
        public void onCropImageDone(String imagePath);
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }
}

SelectPhotoActivity,选择图库

public class SelectPhotoActivity extends Activity implements PhotoAsyncTask.LoaderCallbacks, View.OnClickListener{
    public static final String KEY_INTENT_ALBUM_LIST = "key_intent_album_list";
    public static final String KEY_INTENT_IMAGE_LIST = "key_intent_image_list";
    public static final String KEY_SAVE_ALBUM_LIST = "key_save_album_list";
    public static final String KEY_SAVE_IMAGE_LIST = "key_save_image_list";
    public static final String KEY_IS_DIALOG_MODE = "KEY_IS_DIALOG_MODE";
    private static final int INTENT_RESULT_JUMP_ABLUM_PAGE = 101;
    private GridView mRecyclerView;
    private SelectPhotoAdapter mAdapter;
    private ArrayList mDataList = new ArrayList();
    private ArrayList mBucketList = new ArrayList();

    private boolean mIsDialogMode = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_photo);

        initView();
        initWidget();
        setupListener();
        loadData(savedInstanceState);
    }

    private void initView(){
        mRecyclerView = (GridView)findViewById(R.id.recyclerview);
    }

    private void initWidget(){
        initParams();
        mAdapter = new SelectPhotoAdapter(this, mDataList);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initParams(){
        Intent intent = getIntent();
        if(intent != null){
            mIsDialogMode = intent.getBooleanExtra(KEY_IS_DIALOG_MODE, true);
        }
    }

    private void setupListener(){
        findViewById(R.id.album_tv).setOnClickListener(this);
        findViewById(R.id.close_ib).setOnClickListener(this);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                handleItemClick(position);
            }
        });
    }

    private void handleItemClick(int position){
        Intent data = new Intent();
        ImageItem item = mDataList.get(position);
        String path = item.getPath();
        if(item.getIsCamera() == 1){
            path = "";
        }
        data.putExtra(BaseCameraActivity.INTENT_KEY_IMAGE_PATH, path);
        setResult(RESULT_OK, data);
        finish();
    }

    private void loadData(Bundle savedInstanceState){
        if(savedInstanceState == null){
            new PhotoAsyncTask(this, this, !mIsDialogMode).execute();
        }else{
            onRestoreInstance(savedInstanceState);
        }
    }

   private void onRestoreInstance(Bundle savedInstanceState){
       ArrayList dataList = savedInstanceState.getParcelableArrayList(KEY_SAVE_IMAGE_LIST);
       ArrayList bucketList = savedInstanceState.getParcelableArrayList(KEY_SAVE_ALBUM_LIST);

       DebugTools.d("save2 onRestoreInstance dataList size: " + dataList.size() + " bucketList size: " + bucketList.size());

       mDataList.addAll(dataList);
       mAdapter.notifyDataSetChanged();
       mBucketList.addAll(bucketList);
   }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        DebugTools.d("save2 onSaveInstanceState");
        outState.putParcelableArrayList(KEY_SAVE_IMAGE_LIST, mDataList);
        outState.putParcelableArrayList(KEY_SAVE_ALBUM_LIST, mBucketList);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onLoadFinished(ArrayList dataList, ArrayList bucketList) {
        mDataList.clear();
        mDataList.addAll(dataList);
        mAdapter.notifyDataSetChanged();
        mBucketList.addAll(bucketList);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.album_tv){
            handleClickAlbum();
        }else if(id == R.id.close_ib){
            finish();
        }
    }

    private void handleClickAlbum(){
        jump2AlbumPage(mBucketList);
    }

    private void jump2AlbumPage(ArrayList bucketList){
        Intent intent = new Intent(this, SelectAlbumActivity.class);
        intent.putParcelableArrayListExtra(KEY_INTENT_ALBUM_LIST, bucketList);
        startActivityForResult(intent, INTENT_RESULT_JUMP_ABLUM_PAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case INTENT_RESULT_JUMP_ABLUM_PAGE:
                hanleActivityBackFromAblum(data);
                break;
        }
    }

    private void hanleActivityBackFromAblum(Intent data){
        if(data == null){
            return;
        }
        findViewById(R.id.album_tv).setVisibility(View.INVISIBLE);
        ArrayList dataList = data.getParcelableArrayListExtra(KEY_INTENT_IMAGE_LIST);

        if(dataList != null && dataList.size() > 0){
            mDataList.clear();
            mDataList.addAll(dataList);
            mAdapter.notifyDataSetChanged();
        }
    }
}

SelectAlbumActivity,选择图库里面的专辑

public class SelectAlbumActivity extends Activity {
    public static final String KEY_SAVE_IMAGE_LIST = "key_save_image_list";
    private GridView mRecyclerView;
    private SelectAlbumAdapter mAdapter;
    private ArrayList mDataList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_album);

        initView();
        initWidget();
        setupListener();
        loadData(savedInstanceState);
    }

    private void initView(){
        mRecyclerView = (GridView)findViewById(R.id.recyclerview);
    }

    private void initWidget(){
        mAdapter = new SelectAlbumAdapter(this, mDataList);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setupListener(){
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                handleItemClick(position);
            }
        });

        findViewById(R.id.close_ib).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void handleItemClick(int position){
        Intent data = new Intent();
        data.putParcelableArrayListExtra(SelectPhotoActivity.KEY_INTENT_IMAGE_LIST, mDataList.get(position).getDataList());
        setResult(RESULT_OK, data);
        finish();
    }

    private void loadData(Bundle savedInstanceState){
        if(savedInstanceState == null){
            initParams();
        }else{
            onRestoreInstance(savedInstanceState);
        }
    }

    private void onRestoreInstance(Bundle savedInstanceState){
        ArrayList bucketList = savedInstanceState.getParcelableArrayList(KEY_SAVE_IMAGE_LIST);

        mDataList.addAll(bucketList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList(KEY_SAVE_IMAGE_LIST, mDataList);
        super.onSaveInstanceState(outState);
    }

    private void initParams(){
        Intent intent = getIntent();
        if(intent != null){
            ArrayList dataList = intent.getParcelableArrayListExtra(SelectPhotoActivity.KEY_INTENT_ALBUM_LIST);
            mDataList.clear();
            mDataList.addAll(dataList);
            mAdapter.notifyDataSetChanged();
        }
    }
}

SelectCameraGalleryDialog,弹出是选择图库,还是相机的对话框

public class SelectCameraGalleryDialog extends Dialog implements View.OnClickListener{
    private Context mContext;
    private TextView mCameraTv;
    private TextView mGalleryTv;

    public SelectCameraGalleryDialog(Context context) {
        super(context, R.style.DialogNormalStyle);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = LayoutInflater.from(mContext).inflate(R.layout.library_camera_dialog_select_camera_gallery, null);
        initView(view);
        initWidget();
        setupListener(view);
    }

    private void initView(View view){
        mCameraTv = (TextView)view.findViewById(R.id.camera_type_tv);
        mGalleryTv = (TextView)view.findViewById(R.id.gallery_type_tv);
        setContentView(view);
    }

    private void setupListener(View view){
        mCameraTv.setOnClickListener(this);
        mGalleryTv.setOnClickListener(this);
        view.findViewById(R.id.cancel_tv).setOnClickListener(this);
    }

    private void initWidget(){
        initWidthHeight();
    }


    private void initWidthHeight(){
        int[] arr = getScreenWidthHeight(mContext);
        Window window = this.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = arr[0] * 8 / 9;
        window.setAttributes(params);
        window.setGravity(Gravity.BOTTOM);
    }

    private int[] getScreenWidthHeight(Context context) {
        int[] posArr = new int[2];
        if (context == null) {
            return posArr;
        }

        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;

        posArr[0] = width;
        posArr[1] = height;

        return posArr;
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.camera_type_tv){
            handleClickCameraGallery(true);
        }else if(v.getId() == R.id.gallery_type_tv){
            handleClickCameraGallery(false);
        }else if(v.getId() == R.id.cancel_tv){
            dismiss();
        }
    }

    private void handleClickCameraGallery(boolean isCamera){
        if(mListener != null){
            mListener.onSelectCameraGallery(isCamera);
        }
        dismiss();
    }

    public OnSelectCameraGalleryListener mListener;
    public void setOnSelectCameraGalleryListener(OnSelectCameraGalleryListener listener){
        mListener = listener;
    }
    public interface OnSelectCameraGalleryListener{
        public void onSelectCameraGallery(boolean isCamera);
    }
}

其实也不难,只是封装了一下,下次方便使用

源代码地址:http://download.csdn.net/detail/paddyy/9414162

你可能感兴趣的:(android)