为了账号安全,请及时绑定邮箱和手机立即绑定

Android--选择图片(仿微信发朋友圈)第一篇

标签:
Android

这篇博客主要写仿微信朋友圈选择图片发朋友圈。整个功能包括加载图片,显示图片、相册文件夹、预览图片,九宫格显示已经选择好的图片等等,大概会有三篇博客。

效果图

图片描述

图片描述

看上面的图,加载图片肯定是异步加载,耗时任务。android系统默认提供了一个Loader(Android Loader机制全面详解及源码浅析https://blog.csdn.net/axi295309066/article/details/52536960)请大家搓这篇文章,看了你会对Loader机制会有个全面的认识。在结合我这篇文章,如何去加载相册里的图片? 显示图片是RecyclerView,第一个位置显示的是一个拍照默认的图片,利用RecyclerView支持多种不同类型的布局,把第一个位置单独提取出来,去设置一个只有一张拍照图片的布局。

private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.MINI_THUMB_MAGIC,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
            
                
    //创建一个CursorLoader,去异步加载相册的图片
    @NonNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
        return new CursorLoader(SelectImageActivity.this,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                null, null, IMAGE_PROJECTION[2] + " DESC");
    }

    @Override
    public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
        if (data != null) {
            ArrayList<Image> images = new ArrayList<>();
            //是否显示照相图片
            if (mHasCamera) {
                //添加到第一个的位置(默认)
                images.add(new Image());
            }
            ImageFolder defaultFolder = new ImageFolder();
            defaultFolder.setName("全部照片");
            defaultFolder.setPath("");
            mImageFolders.add(defaultFolder);

            int count = data.getCount();
            if (count > 0) {
                data.moveToFirst();
                do {
                    String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                    long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    int id = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    String thumbPath = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    String bucket = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));

                    Image image = new Image();
                    image.setPath(path);
                    image.setName(name);
                    image.setDate(dateTime);
                    image.setId(id);
                    image.setThumbPath(thumbPath);
                    image.setFolderName(bucket);

                    images.add(image);

                    //如果是被选中的图片
                    if (mSelectedImages.size() > 0) {
                        for (Image i : mSelectedImages) {
                            if (i.getPath().equals(image.getPath())) {
                                image.setSelect(true);
                            }
                        }
                    }
                    //设置图片分类的文件夹
                    File imageFile = new File(path);
                    File folderFile = imageFile.getParentFile();
                    ImageFolder folder = new ImageFolder();
                    folder.setName(folderFile.getName());
                    folder.setPath(folderFile.getAbsolutePath());
                    if (!mImageFolders.contains(folder)) {
                        folder.getImages().add(image);
                        //默认相册封面
                        folder.setAlbumPath(image.getPath());
                        mImageFolders.add(folder);
                    } else {
                        // 更新
                        ImageFolder imageFolder = mImageFolders.get(mImageFolders.indexOf(folder));
                        imageFolder.getImages().add(image);
                    }
                } while (data.moveToNext());
            }
            addImagesToAdapter(images);
            //全部照片
            defaultFolder.getImages().addAll(images);
            if (mHasCamera) {
                defaultFolder.setAlbumPath(images.size() > 1 ? images.get(1).getPath() : null);
            } else {
                defaultFolder.setAlbumPath(images.size() > 0 ? images.get(0).getPath() : null);
            }
            //删除掉不存在的,在于用户选择了相片,又去相册删除
            if (mSelectedImages.size() > 0) {
                List<Image> rs = new ArrayList<>();
                for (Image i : mSelectedImages) {
                    File f = new File(i.getPath());
                    if (!f.exists()) {
                        rs.add(i);
                    }
                }
                mSelectedImages.removeAll(rs);
            }
        }
        mImageFolderView.setImageFolders(mImageFolders);
        addImageFoldersToAdapter();
    }

    @Override
    public void onLoaderReset(@NonNull Loader<Cursor> loader) {

    }
};

以上代码主要是如何加载图片,设置图片的不同类型文件夹,我们打开系统相册也可以看到不同类型的图片文件夹。

图片描述

看这张图,这个相册文件夹是一个自定义的View,包含了两个部分,一个是ShadowView,显示时会有个阴影部分,二是显示相册文件夹(RecyclerView)。相册文件夹的显示和隐藏是一个平移动画,并不是一个Dialog或者PopupWindow。

ImageFolderView

public class ImageFolderView extends FrameLayout implements OnItemClickListener {
private View mShadowView;
private String mShadowViewColor = "#50000000";
private RecyclerView mImageFolderRv;
private List<ImageFolder> mImageFolders;
private ImageFolderViewListener mListener;
private int mImageFolderHeight;
private boolean mShow;

public ImageFolderView(Context context) {
    this(context, null);
}

public ImageFolderView(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, 0);
}

public ImageFolderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mShadowView = new View(context);
    mShadowView.setBackgroundColor(Color.parseColor(mShadowViewColor));
    mImageFolderRv = ( RecyclerView ) inflate(context, R.layout.image_folder_layout, null);
    //设置LayoutParams
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT);
    layoutParams.gravity = Gravity.BOTTOM;
    mImageFolderRv.setLayoutParams(layoutParams);
    //设置布局管理器setLayoutManager
    mImageFolderRv.setLayoutManager(new LinearLayoutManager(context));
    addView(mShadowView);
    addView(mImageFolderRv);
    //开始不显示阴影
    mShadowView.setAlpha(0f);
    mShadowView.setVisibility(GONE);

}

public void setImageFolders(List<ImageFolder> imageFolders) {
    mImageFolders = imageFolders;
}

public void setAdapter(ImageFolderAdapter adapter) {
    if (adapter == null) {
        throw new NullPointerException("adapter not null!");
    }
    mImageFolderRv.setAdapter(adapter);
    adapter.setItemClickListener(this);
}

public void setListener(ImageFolderViewListener listener) {
    this.mListener = listener;
}

/**
 * 显示
 */
public void show() {
    if (mShow) {
        return;
    }
    if (mListener != null) {
        mListener.onShow();
    }
    mShow = true;
    mShadowView.setVisibility(VISIBLE);
    ObjectAnimator animator = ObjectAnimator.ofFloat(mImageFolderRv,
            "translationY", mImageFolderHeight, 0);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(388);
    animator.start();

    ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mShadowView, "alpha", 0f, 1f);
    alphaAnimator.setDuration(388);
    alphaAnimator.start();

}

/**
 * 隐藏
 */
public void hide() {
    if (!mShow) {
        return;
    }
    if (mListener != null) {
        mListener.onDismiss();
    }
    ObjectAnimator animator = ObjectAnimator.ofFloat(mImageFolderRv,
            "translationY", 0, mImageFolderHeight);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(388);
    animator.start();

    ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mShadowView, "alpha", 1f, 0f);
    alphaAnimator.setDuration(388);
    alphaAnimator.start();

    alphaAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            mShow = false;
            mShadowView.setVisibility(GONE);

        }
    });
}

public boolean isShowing() {
    return mShow;
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    //获取高度
    int height = MeasureSpec.getSize(heightMeasureSpec);
    mImageFolderHeight = ( int ) (height * 0.9f);
    ViewGroup.LayoutParams params = mImageFolderRv.getLayoutParams();
    params.height = mImageFolderHeight;
    mImageFolderRv.setLayoutParams(params);
    //开始的时候,移下去
    mImageFolderRv.setTranslationY(mImageFolderHeight);
}


@Override
public void onItemClick(int position) {
    if (mListener != null) {
        mListener.onSelect(this, mImageFolders.get(position));
        hide();
    }
}

public interface ImageFolderViewListener {
    void onSelect(ImageFolderView imageFolderView, ImageFolder imageFolder);

    void onDismiss();

    void onShow();
}}

只是粘贴了部分代码和提供了思路,实现了大体的功能。还有的就是选择具体的图片、预览图片,九宫格动态显示已经选择好的图片等等。对RecyclerView的封装,没有写,我是拿来直接用的,因为对RecyclerView的封装很早之前就写好了,现在我对RecycleView封装和扩展会做成一个Module,直接导入到项目中使用。大家可以看看源码,看我是如何封装RecycleView的。这个SelectImage的Demo,对RecycleView封装和扩展并不是很全,但是大家可以先看看基础的,抽取公共的ViewHolder和Adapter,怎么去添加分割线。

点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消