I'm dev an app that use a recycler view to show items composed by an image and a text. The user can add an item with a custom image, doing this in a normal activity it's easy:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
launcher.launch(intent);
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK
&& result.getData() != null) {
Uri photoUri = result.getData().getData();
image_to_up = photoUri;
image_uploaded = true;
element_image_add.setImageURI(photoUri);
}
}
);
But if I want let the user edit a recycler view item image, then the same code wont work inside the custom adapter, I get:
Cannot resolve method 'registerForActivityResult' in Adapter
So, how can I do it? How can I let the user open the gallery and select an image inside a custom adapter class?
Define this in your Activity class:
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK
&& result.getData() != null) {
Uri photoUri = result.getData().getData();
image_to_up = photoUri;
image_uploaded = true;
element_image_add.setImageURI(photoUri);
}
}
);
and then create a function in the activity class that call this launcher, then call this function from the adapter class:
public void launch_func() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
launcher.launch(intent);
}
Basically you can't call the method inside the adapter so you call it from your activity class, it's not the prettiest but it should works.