Android 使用ActivityResultLauncher选择图片并显示
一、添加权限
在Android的Fragment\Activity中使用Button选取图片并显示在ImageView中,需要在AndroidManifest.xml文件中添加相机和存储的权限。
1.在较久版本的sdk时
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="24"/>
2.在较新版本的sdk时
编辑时使用的版本为sdk最新版本(34),使用的是 ActivityResultLauncher
实现。Activity Result API
是官方用于替代 startActivityForResult()
和 onActivityResult()
的工具。以下代码最低现已适配 Android 10。
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
二、实现Button点击事件
在Fragment的onCreateView()或者直接在Fragment中实现Button的点击事件。(Activity同理)
private ActivityResultLauncher<Intent> selectImageLauncher;
private ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
imageView = view.findViewById(R.id.image_home);
Button selectImageButton = view.findViewById(R.id.btn_home_select);
// 为按钮设置点击事件
selectImageButton.setOnClickListener(v -> {
// 创建一个Intent来选择图片,并检查获取权限
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// 启动ActivityResultLauncher
selectImageLauncher.launch(intent);
});
return view;
}
三、实现图片选取并显示方法
之前较久版本使用的是startActivityForResult,该方法已弃用,替换为ActivityResultLauncher
// 注册ActivityResultLauncher来处理结果,选择图片
selectImageLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
// 图片的Uri
Uri imageUri = result.getData().getData();
// 设置ImageView显示选中的图片
imageView.setImageURI(imageUri);
}
});
四、实现多个图片或者视频选取并显示方法
只有 GetMultipleContentsLauncher
可以选择,对应 Intent
的 action
是 Intent.ACTION_GET_CONTENT
。Intent.ACTION_PICK
不支持多选。
选择图片调用 launchForImage()
,选择视频调用 launchForVideo()
。
getMultipleContentsLauncher.launchForImage(
(uris) -> {
if (uris.size() > 0) {
// 处理 uri 列表
}
},
(settingsLauncher) -> {
// 拒绝了读取权限且不再询问,可引导用户到设置里授权该权限
},
() -> {
// (可选)拒绝了一次读取权限,可弹框解释为什么要获取该权限
}
);