如图效果。使用gridview显示选取的图片,在getItem中根据图片数判断返回的item数量如果未达到最大数量就加一用于显示带加号的图片,如果达到最大数则返回原始item数量!
class MyGridViewAdapter extends BaseAdapter {
Context mContext;
public MyGridViewAdapter(Context mContext) {
this.mContext = mContext;
}
@Override
public int getCount() {
if (imgList.size() == 5) {
return 5;
} else {
return imgList.size() + 1;
}
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
MyHolder holder = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.upload_img_item, null);
holder = new MyHolder();
holder.img = (ImageView) view.findViewById(R.id.iv_add);
holder.imgDelete = (ImageView) view.findViewById(R.id.iv_delete);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (MyHolder) view.getTag();
}
if (imgList.size() == i) {//如果imgList.size为5,i最大只能到4
holder.progressBar.setVisibility(View.GONE);
holder.imgDelete.setVisibility(View.GONE);
Glide.with(mContext).load(R.drawable.ic_salary2_11).dontAnimate().into(holder.img);
if (i == 5) {//如果imgList.size为5,i最大只能到4,以防万一,多加一步判断
holder.img.setVisibility(View.GONE);
}
//点击选取图片
holder.img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请READ_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(PromotiongRaphicActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_EXTERNAL_STORAGE_REQUEST_CODE);
}else {
Matisse.from(PromotiongRaphicActivity.this)
.choose(MimeType.allOf())
.countable(true)
.maxSelectable(5 - imgList.size())
.gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.size_100dp))
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
.thumbnailScale(1f)
.imageEngine(new GlideEngine())
.theme(R.style.Matisse_Zhihu)
.forResult(PICKIMAGE);
}
}
});
} else {
File imgFile = new File(CommonUtils.getRealFilePathFromUri(mContext,imgList.get(i)));
Glide.with(mContext).load(imgFile).dontAnimate().into(holder.img);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//删除图片
imgList.remove(i);
notifyDataSetChanged();
}
});
holder.img.setClickable(false);
}
return view;
}
}
class MyHolder {
ImageView img;
ImageView imgDelete;
ProgressBar progressBar;
}