如何用ActivityResultLauncher替换它。对不起,伙计们,我只是编码和编程的新手。
SelectImageGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
}
});
您需要使用以下Kotlin
代码在onCreate
之外注册活动结果
val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
// Callback after selecting image
// Do whatever you want to do with uri
}
}
}
现在,当您想打开库来拾取图像时,不需要startActivityForResult(..)
调用下面的方法
getContent.launch("image/*")
SelectImageGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
result.launch(Intent.createChooser(intent, "Select Image From Gallery"));
}
});
在与侦听器相同的方法中:
ActivityResultLauncher<String> result = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri result) {
//DO whatever with received image content scheme Uri
}
});