Android 图片选择框架 点击放大(可添加多个item,可删除)

一.这个功能相信每个小伙伴都会遇到,话不多说,直接上效果图(花屏是录屏软件的原因)与步骤,以供小伙伴们参考。

嘿嘿嘿!.gif

1.依赖:

//图片选择器
compile 'com.jph.takephoto:takephoto_library:4.0.3'
//仿iOS的AlertViewController 
compile 'com.bigkoo:alertview:1.0.3'
//最新版本Glide
compile 'com.github.bumptech.glide:glide:3.7.0'
//design中包含的RecycleView
compile 'com.android.support:design:25.3.1'
//ButterKnife
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//photoView 图片放大控件
compile 'com.github.chrisbanes:PhotoView:1.3.0'

2.xml文件布局:

      <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleview_check"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></android.support.v7.widget.RecyclerView>

3.当前Activity中初始化代码:

    RecycleView recyCheck =(Recycleview)findViewById(R.id.recycleview_check);
    //设置展示框中单行展示的图片个数
    recyCheck.setLayoutManager(new GridLayoutManager(this, 5));
    //初始化自定义Adapter,onAddPicListener是添加图片的点击监听器,onPicClickListener是添加图片成功以后,点击放大的监听器。
    photoAdapter = new PhotoAdapter(this, onAddPicListener, onPicClickListener);
    //设置多选时最多选择的图片张数
    photoAdapter.setSelectMax(5);
    recyCheck.setAdapter(photoAdapter);

其中,PhotoAdapter代码如下:

public class PhotoAdapter extends
    RecyclerView.Adapter<PhotoAdapter.ViewHolder> {

private int selectMax = 3;
public final int TYPE_CAMERA = 1;
public final int TYPE_PICTURE = 2;

private Context mContext;
private LayoutInflater mInflater;
private List<TImage> list = new ArrayList<>();


//点击添加图片跳转
private onAddPicListener mOnAddPicListener;

public interface onAddPicListener {
    void onAddPicClick(int type, int position);
}

//点击图片放大
private onPicClickListener mOnPicClickListener;

public interface onPicClickListener {
    void onPicClick(View view, int position);
}

public PhotoAdapter(Context context, onAddPicListener mOnAddPicListener, onPicClickListener mOnPicClickListener) {
    mInflater = LayoutInflater.from(context);
    this.mContext = context;
    this.mOnAddPicListener = mOnAddPicListener;
    this.mOnPicClickListener = mOnPicClickListener;
}

public void setSelectMax(int selectMax) {
    this.selectMax = selectMax;
}

public void setList(List<TImage> list) {
    this.list = list;
}

public class ViewHolder extends RecyclerView.ViewHolder {

    ImageView mPhoto_image;
    ImageView mPhoto_del;

    public ViewHolder(View view) {
        super(view);
        mPhoto_image = (ImageView) view.findViewById(R.id.photo_image);
        mPhoto_del = (ImageView) view.findViewById(R.id.photo_del);
    }
}

@Override
public int getItemCount() {
    if (list.size() < selectMax) {
        return list.size() + 1;
    } else {
        return list.size();
    }
}

@Override
public int getItemViewType(int position) {
    if (isShowAddItem(position)) {
        return TYPE_CAMERA;
    } else {
        return TYPE_PICTURE;
    }
}

/**
 * 创建ViewHolder
 */
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = mInflater.inflate(R.layout.activity_photo_item,
            viewGroup, false);
    final ViewHolder viewHolder = new ViewHolder(view);

    return viewHolder;
}

private boolean isShowAddItem(int position) {
    int size = list.size() == 0 ? 0 : list.size();
    return position == size;
}

/**
 * 设置值
 */
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
    //少于3张,显示继续添加的图标
    Log.d("...", "onBindViewHolder: " + position);
    if (getItemViewType(position) == TYPE_CAMERA) {
        //设置添加按钮图片的样式
        viewHolder.mPhoto_image.setImageResource(R.mipmap.icon_addpic);
        viewHolder.mPhoto_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnAddPicListener.onAddPicClick(0, viewHolder.getAdapterPosition());
            }
        });
        viewHolder.mPhoto_del.setVisibility(View.INVISIBLE);
    } else {
        viewHolder.mPhoto_del.setVisibility(View.VISIBLE);
        viewHolder.mPhoto_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnPicClickListener.onPicClick(view, viewHolder.getAdapterPosition());
            }
        });
        viewHolder.mPhoto_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnAddPicListener.onAddPicClick(1, viewHolder.getAdapterPosition());
            }
        });

        Glide.with(mContext)
                .load(list.get(position).getCompressPath())
                .crossFade()
                .into(viewHolder.mPhoto_image);
    }
  }  
}

PhotoAdapter中所依赖的xml文件如下:

  <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true">
<ImageView
    android:id="@+id/photo_image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="centerCrop"
    android:src="@color/image_color" />

<ImageView
    android:id="@+id/photo_del"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|top"
    android:scaleType="center"
    android:src="@mipmap/icon_delete" />
</FrameLayout>

添加图片的点击监听器onAddPicListener 代码及所调用方法如下:

private List<TImage> selectMedia = new ArrayList<>();
private List<TImage> updateMedia = new ArrayList<>();
ArrayList<String> imageUrls = new ArrayList<>();
private List<String> internetUrls = new ArrayList<>();
private PhotoAdapter.onAddPicListener onAddPicListener = new PhotoAdapter.onAddPicListener() {
    @Override
    public void onAddPicClick(int type, int position) {
        switch (type) {
            case 0: //点击图片
                new AlertView("上传图片", null, "取消", null,
                        new String[]{"拍照", "从相册中选择"},
                        MainActivity.this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        TakePhoto takePhoto = getTakePhoto();
                        //获取TakePhoto图片路径
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                             d(TAG, "SD卡可用");

                            File file = new File(Environment.getExternalStorageDirectory(), "/photo/" + System.currentTimeMillis() + ".jpg");
                            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                            Uri imageUri = Uri.fromFile(file);
                            d(TAG, "文件创建成功并获取URL == " + imageUri);
                            //设置takephoto的照片使用压缩
                            configCompress(takePhoto);
                            //设置Takephoto 使用TakePhoto自带的相册   照片旋转角度纠正
                            configTakePhotoOption(takePhoto);
                            switch (position) {
                                case 0:  //拍照
                                    takePhoto.onPickFromCapture(imageUri);
                                    break;
                                case 1:  //相册选择
                                    //如果已展示图片的个数为0,就设置多选时最多选中3张
                                    if (selectMedia.size() == 0) { 
                                        takePhoto.onPickMultiple(3);
                                    //如果已展示图片的个数为1,就设置多选时最多选中2张
                                    } else if (selectMedia.size() == 1) {
                                        takePhoto.onPickMultiple(2);
                                   //如果已展示图片的个数为2,就设置多选时最多选中1张
                                    } else if (selectMedia.size() == 2) {
                                        takePhoto.onPickMultiple(1);
                                    }
                                    break;
                            }
                        } else {
                            Log.d(TAG, "SD卡bu可用");
                        }

                    }
                }).show();
                break;
            case 1:  //点击删除按钮
                
                    selectMedia.remove(position);
                    photoAdapter.notifyItemRemoved(position);
                    internetUrls.remove(position);

                break;
        }
    }
};
//设置Takephoto 使用TakePhoto自带的相册   照片旋转角度纠正
private void configTakePhotoOption(TakePhoto takePhoto) {
    TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
    builder.setWithOwnGallery(true);
    builder.setCorrectImage(true);
    takePhoto.setTakePhotoOptions(builder.create());
}

//设置takephoto的照片使用压缩
private void configCompress(TakePhoto takePhoto) {
    CompressConfig config;
    config = new CompressConfig.Builder()
            .setMaxSize(102400)
            .setMaxPixel(800)
            .enableReserveRaw(true)
            .create();
    takePhoto.onEnableCompress(config, false);
}
/**
 * 获取TakePhoto实例
 * 没有继承TakePhotoActivity 所写
 */
public TakePhoto getTakePhoto() {
    if (takePhoto == null) {
        takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
    }
    return takePhoto;
}

getTakePhoto中会报错,此时,我们让当前Activity实现InvokeListener与TakePhoto.TakeResultListener接口,重写invoke与方法,重写以下方法代码如下:

image.png

@Override
public void takeCancel() {
    Log.d(TAG, "takeCancel");
}

@Override
public void takeFail(TResult result, String msg) {
    ArrayList<TImage> images = result.getImages();
    showImg(result.getImages());
    Log.d(TAG, "takeFail" + images.get(0).toString());
}

@Override
public void takeSuccess(TResult result) {
    showImg(result.getImages());
}

//没有继承TakePhotoActivity 所写
@Override
protected void onSaveInstanceState(Bundle outState) {
    getTakePhoto().onSaveInstanceState(outState);
    super.onSaveInstanceState(outState);
}

//没有继承TakePhotoActivity 所写
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
}

//没有继承TakePhotoActivity 所写
@Override
public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
    PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
    if (PermissionManager.TPermissionType.WAIT.equals(type)) {
        this.invokeParam = invokeParam;
    }
    return type;
}


//图片成功后返回执行的方法
private void showImg(ArrayList<TImage> images) {
    Log.d(TAG, images.toString());
    //目的是防止上传重复的图片
    updateMedia.clear();

    for (int i = 0; i < images.size(); i++) {
        if (images.get(i).getCompressPath() != null) {
            selectMedia.add(images.get(i));
            updateMedia.add(images.get(i));
        }
    }
    if (selectMedia != null) {
        photoAdapter.setList(selectMedia);
        photoAdapter.notifyDataSetChanged();
    }
    //需上传图片,请使用用updateMedia数组。
}

回过头来看,既然照相肯定有回调,我们应当在当前Activity中重写回调方法,并交给takePhoto来操作

   //没有继承TakePhotoActivity 所写
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //将拍照返回的结果交给takePhoto处理
    getTakePhoto().onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}

图片点击放大监听器onPicClickListener代码如下:

 //图片点击事件
private PhotoAdapter.onPicClickListener onPicClickListener = new PhotoAdapter.onPicClickListener() {
    @Override
    public void onPicClick(View view, int position) {
        imageUrls.clear();
        for (int i = 0; i < selectMedia.size(); i++) {
            String compressPath = selectMedia.get(i).getCompressPath();
            imageUrls.add(compressPath);
        }
        imageBrower(position, imageUrls);
    }
};
 private void imageBrower(int position, ArrayList<String> imageUrls) {
    Intent intent = new Intent(this, ImagePagerActivity.class);
    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, imageUrls);
    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
    startActivity(intent);
}

我们可以看到,图片点击以后跳转到了另一个Activity,这个Activity就是我们专门用来放大图片的Activity了,使用的方法很简单,传入需要展示的图片数组和你点击的图片索引,就会自动选中对应的图片进行展示并具备左右滑动切换图片的效果,代码如下(可当作工具类使用,应用于项目各个需要展示图片数组的位置,调用imageBrower方法即可):

public class ImagePagerActivity extends FragmentActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String EXTRA_IMAGE_INDEX = "image_index";
public static final String EXTRA_IMAGE_URLS = "image_urls";

@BindView(R.id.indicator)
TextView indicator;
@BindView(R.id.pager)
HackyViewPager pager;

private int pagerPosition;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_detail_pager);
    ButterKnife.bind(this);
    MyUtils.setSystemColor(this,R.color.bg_shouye);

    pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
    ArrayList<String> urls = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLS);
    ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), urls);
    pager.setAdapter(mAdapter);
    CharSequence text = getString(R.string.viewpager_indicator, 1, pager.getAdapter().getCount());
    indicator.setText(text);
    // 更新下标
    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, pager.getAdapter().getCount());
            indicator.setText(text);
        }
    });
    if (savedInstanceState != null) {
        pagerPosition = savedInstanceState.getInt(STATE_POSITION);
    }
    pager.setCurrentItem(pagerPosition);

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(STATE_POSITION, pager.getCurrentItem());
}

private class ImagePagerAdapter extends FragmentStatePagerAdapter {
    public ArrayList<String> fileList;

    public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
        super(fm);
        this.fileList = fileList;
    }

    @Override
    public int getCount() {
        return fileList == null ? 0 : fileList.size();
    }

    @Override
    public Fragment getItem(int position) {
        String url = fileList.get(position);
        return ImageDetailFragment.newInstance(url);
    }
  }
}

ImagePagerActivity 对应的xml文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/bg_shouye"
>

<com.mihomes.checkphotodemo.HackyViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black" />

<TextView
    android:id="@+id/indicator"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="@android:color/transparent"
    android:gravity="center"
    android:text="@string/viewpager_indicator"
    android:textColor="@android:color/white"
    android:textSize="18sp" />
</LinearLayout>

HackyViewPager是一个重写了ViewPager的自定义类,解决了PhotoView和ViewPager的滑动冲突,代码如下:

public class HackyViewPager extends ViewPager {
  private static final String TAG = "HackyViewPager";
  public HackyViewPager(Context context) {
    super(context);
}

public HackyViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    try {
        return super.onInterceptTouchEvent(ev);
    } catch (IllegalArgumentException e) { // 不理会
        Log.e(TAG, "hacky viewpager error1");
        return false;
    } catch (ArrayIndexOutOfBoundsException e) {
        // 不理会
        Log.e(TAG, "hacky viewpager error2");
        return false;
    }
  }
}

同时,ImagePagerActivity中所引用的ImageDetailFragment代码如下:

public class ImageDetailFragment extends Fragment {
private static final String TAG = "ImageDetailFragment";
private String mImageUrl;
private PhotoView mImageView;
private ProgressBar progressBar;
private PhotoViewAttacher mAttacher;
private Dialog dialog;
private Button save;
private Button saveCancel;
public static ImageDetailFragment newInstance(String imageUrl) {
    final ImageDetailFragment f = new ImageDetailFragment();
    final Bundle args = new Bundle();
    args.putString("url", imageUrl);
    f.setArguments(args);
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mImageUrl = getArguments() != null ? getArguments().getString("url") : null;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
    mImageView = (PhotoView) v.findViewById(R.id.maxphoto_image);
    mAttacher = new PhotoViewAttacher(mImageView);
    mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
        @Override
        public void onPhotoTap(View arg0, float arg1, float arg2) {
            getActivity().finish();
        }

        @Override
        public void onOutsidePhotoTap() {

        }
    });

    progressBar = (ProgressBar) v.findViewById(R.id.maxphoto_loading);
    Glide.with(getContext()).load(mImageUrl).into(mImageView);
    mAttacher.update();
    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

  }
}

ImageDetailFragment所引用的xml文件代码如下:

<?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:background="@color/bg_shouye">

<uk.co.senab.photoview.PhotoView
    android:id="@+id/maxphoto_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

<ProgressBar
    android:id="@+id/maxphoto_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:visibility="gone" />
</LinearLayout>

最后,莫要忘了在清单文件(AndroidManifest.xml)中声明我们所引用的ImagePagerActivity:

<activity android:name=".ImagePagerActivity"></activity>

该Demo中所用的色值属性如下:

<color name="image_color">#f6f6f6</color>
<color name="bg_shouye">#333333</color>

文字属性如下:

  <string name="viewpager_indicator">指示器</string>

二.值得一提的是,takePhoto多选框修改样式的方法如下

自定义相册

如果TakePhoto自带相册的UI不符合你应用的主题的话,你可以对它进行自定义。方法如下:

自定义Toolbar

在“res/layout”目录中创建一个名为“toolbar.xml”的布局文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/CustomToolbarTheme"
    android:background="#ffa352">
</android.support.v7.widget.Toolbar>

在“toolbar.xml”文件中你可以指定TakePhoto自带相册的主题以及Toolbar的背景色。

自定义状态栏

在“res/values”目录中创建一个名为“colors.xml”的资源文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="multiple_image_select_primaryDark">#212121</color>
</resources>

通过上述方式便可以自定义状态栏的颜色。

自定义提示文字

在“res/values”目录的“string.xml”文件冲添加如下代码:

<resources>    
    <string name="album_view">选择图片</string>
    <string name="image_view">单击选择</string>
    <string name="add">确定</string>
    <string name="selected">已选</string>
    <string name="limit_exceeded">最多能选 %d 张</string>
</resources>

重写上述代码,便可以自定义TakePhoto自带相册的提示文字。

自定义标题栏颜色

在styles.xml里面重写以下style即可:

<style name="MultipleImageSelectTheme"
 parent="Theme.AppCompat.Light.NoActionBar"> 
 <item name="colorPrimary">@color/multiple_image_select_primary</item>//标题栏颜色
 <item name="colorPrimaryDark">@color/multiple_image_select_primaryDark</item> //状态栏颜色          
 <item name="colorAccent">@color/multiple_image_select_accent</item> 
 <item name="actionModeStyle">@style/CustomActionModeStyle</item>
 <item name="windowActionModeOverlay">true</item>
 <item name="actionMenuTextColor">@android:color/white</item>   //标题栏文字颜色
</style>
<style name="CustomActionModeStyle" parent="Base.Widget.AppCompat.ActionMode">
    <item name="background">@color/rdb_bg</item>  //选中标题栏背景颜色
</style>

三.本项目GitHub地址:https://github.com/MiHomes/checkPhotoDemo

猜你喜欢

转载自blog.csdn.net/u014644594/article/details/84103940