I have multiple ImageViews in a fragment in my application. I want the user to select an image for each imageView. The question is, I don't know for which ImageView the user selected an image.
I thought that if I add a request code, I can fix this problem according to the code received.
I can't add request code to the method I'm using for the user to select an image.
I do a permission check first when the button is pressed , I open the gallery if it's permission granted. :
// First ImageView onClick
bind.addQuestionImage.setOnClickListener{
if (!checkPermission())
requestSinglePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
else openGallery()
}
// Second ImageView onClick
bind.addAnswerImage.setOnClickListener{
if (!checkPermission())
requestSinglePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
else openGallery()
}
My Permission request method :
private fun checkPermission() = ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
The method where I listen to the response to the request :
private val requestSinglePermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
toaster("Permission Granted.")
} else {
toaster("Permission Denied.")
}
}
I open the gallery if the user has permission :
private fun openGallery(){
val galleryIntent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
getContent.launch(galleryIntent)
}
I get the content in this method :
// get content
private val getContent =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
val myUri : Uri? = it.data?.data
// Which ImageView is this incoming uri ?
}
How can I solve this problem ? Or is there a better method ?