在compileSDK = 33 时,谷歌在安卓新增了 图片选择器 功能,支持单选、多选、选图片、视频等操作,并且不需要额外获取照片/音频权限。
具体实现如下:
1:请求
Log.d(TAG, "Build.VERSION.SDK_INT" + Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT >= 33) {
//图片选择器单选
// Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
// 在complieSDK32已废弃
// startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
//图片选择器多选
final int maxNumPhotosAndVideos = 3;
Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
// intent.setType("video/*");//仅选择视频
intent.setType("image/*");//仅选择图片
intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
launcher.launch(intent);
} else {
//我们需要自己开发
}
2:响应
单选文章来源:https://www.toymoban.com/news/detail-722021.html
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PHOTO_PICKER_REQUEST_CODE) {
Uri currentUri = null;
if (data != null) {
currentUri = data.getData();
binding.image.setImageURI(currentUri);
}
Log.d(TAG, "currentUri:" + currentUri);
}
}
}
多选文章来源地址https://www.toymoban.com/news/detail-722021.html
launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
if (result.getData() != null && result.getResultCode() == RESULT_OK) {
Intent intent = result.getData();
for (int i = 0; i < intent.getClipData().getItemCount(); i++) {
Uri uri = intent.getClipData().getItemAt(i).getUri();
Log.d(TAG, "multiple current Uri:" + uri);
// Do stuff with each photo/video URI.
}
}
}
}
});
到了这里,关于Android13-图片选择器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!