![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8717c8a35eb7eca3683c6f4fc3176e26.gif#pic_center)
![](https://i-blog.csdnimg.cn/blog_migrate/6eac9253ea4a2e754fa48193b1aa3058.jpeg)
实现思路
实现起来其实非常简单
我利用recyclerview工具,多item布局,在layoutmanager中设置三个一行,利用回调方法监听添加图片的方法
并设置list的添加顺序使得加号始终处于最后一个。然后限制list最大长度为9,使得加载最多为9张图片
下面直接把代码放上
MainActivity.java
package com.example.ninegriddemo;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.CursorLoader;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private NineGridAdapter nineGridAdapter;
private Uri photoUri; //相机拍照返回图片路径
private File outputImage;
private static final int GET_BACKGROUND_FROM_CAPTURE_RESOULT = 1;
private static final int RESULT_REQUEST_CODE = 2;
private static final int TAKE_PHOTO = 3;
final List<Map<String,Object>> list = new ArrayList<>();
private void selectCamera() {
//创建file对象,用于存储拍照后的图片,这也是拍照成功后的照片路径
outputImage = new File(this.getExternalCacheDir(), "camera_photos.jpg");
try {
//判断文件是否存在,存在删除,不存在创建
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
photoUri = Uri.fromFile(outputImage);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, TAKE_PHOTO);
}
public static final String STR_IMAGE = "image/*";
//选择相册
private void selectPhoto(){
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STR_IMAGE);
startActivityForResult(intent, GET_BACKGROUND_FROM_CAPTURE_RESOULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case RESULT_REQUEST_CODE: //相册返回
final String selectPhoto = getRealPathFromUri(this,cropImgUri);
int size=list.size();
list.remove(size-1);
Map<String,Object> map=new HashMap