用java代码实现安卓13的照片选择器代码
时间: 2023-07-03 15:14:12 浏览: 110
以下是使用Android官方提供的图片选择器库实现的示例代码:
1. 首先,在app的build.gradle文件中添加以下依赖:
```groovy
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.github.bumptech.glide:compiler:4.8.0'
implementation 'com.yalantis:ucrop:2.2.2'
}
```
2. 在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
3. 创建一个Activity用于选择图片,例如SelectImageActivity.java:
```java
public class SelectImageActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SELECT_IMAGE = 100;
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mAdapter = new ImageAdapter(this);
mRecyclerView.setAdapter(mAdapter);
findViewById(R.id.btn_select_image).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_SELECT_IMAGE && data != null) {
Uri uri = data.getData();
if (uri != null) {
startCrop(uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCrop(Uri uri) {
String destinationFileName = "crop_image.jpg";
UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName)));
uCrop.withAspectRatio(1, 1);
uCrop.withMaxResultSize(800, 800);
uCrop.start(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
mAdapter.onDestroy();
}
}
```
4. 创建一个Adapter用于显示图片,例如ImageAdapter.java:
```java
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private Context mContext;
private List<String> mImages;
private RequestOptions mRequestOptions;
private OnItemClickListener mListener;
private Disposable mDisposable;
public interface OnItemClickListener {
void onItemClick(String imagePath);
}
public ImageAdapter(Context context) {
mContext = context;
mRequestOptions = new RequestOptions()
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL);
mImages = new ArrayList<>();
mDisposable = Observable.just("")
.observeOn(Schedulers.io())
.map(new Function<String, List<String>>() {
@Override
public List<String> apply(String s) throws Exception {
return getImagePaths();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<String>>() {
@Override
public void accept(List<String> strings) throws Exception {
mImages.clear();
mImages.addAll(strings);
notifyDataSetChanged();
}
});
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_image, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String imagePath = mImages.get(position);
Glide.with(mContext)
.load(new File(imagePath))
.apply(mRequestOptions)
.into(holder.imageView);
}
@Override
public int getItemCount() {
return mImages.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public void onDestroy() {
mDisposable.dispose();
}
private List<String> getImagePaths() {
List<String> paths = new ArrayList<>();
String[] projection = new String[]{MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Media.DATE_ADDED + " DESC");
if (cursor != null) {
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
paths.add(path);
}
cursor.close();
}
return paths;
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClick(mImages.get(getAdapterPosition()));
}
}
});
}
}
}
```
5. 创建一个布局文件用于显示图片,例如item_image.xml:
```xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
6. 创建一个布局文件用于选择图片,例如activity_select_image.xml:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/btn_select_image"
android:scrollbars="vertical"/>
<Button
android:id="@+id/btn_select_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="选择图片"/>
</RelativeLayout>
```
7. 在需要调用图片选择器的地方,启动SelectImageActivity:
```java
Intent intent = new Intent(this, SelectImageActivity.class);
startActivity(intent);
```
以上就是使用Android官方提供的图片选择器库实现安卓13的照片选择器代码的示例。
阅读全文