skip to Main Content

As startActivityForResult() has been depreciated .How to get image from gallery in android with kotlin ?

2

Answers


  1. You can use registerForActivityResult instead of startActivityForResult.
    Here is my code to get image from gallery in kotlin:

    // class level
    private val openGallery =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    binding.imgProfile.load(it.data?.data)
                }
            }
    
    // in onViewCreated
    imgProfile.setOnClickListener {
                val intent = Intent(Intent.ACTION_PICK)
                intent.setType("image/*")
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                openGallery.launch(intent)
            }
    
    Login or Signup to reply.
  2. // on button Lisnter put this code

    buttonPressed.setOnClickListener {
                    val intent = Intent(Intent.ACTION_PICK)
                    intent.type = "image/*"
                    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    openGallery.launch(intent)            
            }
    

    // outside onCreate put this code

    private val openGallery =     registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    backgroundImage.setImageURI(it.data?.data)
                }
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search