ActivityResultContract to pick/take a photo in Kotlin

2.7k Views Asked by At

How can i use ActivityResultContract (Kotlin) in order to pick a photo from the gallery OR to take a photo by the camera using only one button?

1

There are 1 best solutions below

4
On

Pick an image from the gallery:

class TestActivity: AppCompatActivity() {

    private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { imageUri ->
            // Suppose you have an ImageView that should contain the image:
            imageView.setImageURI(imageUri)
        }
    }

    private fun onButtonClicked() {
        getContent.launch("image/*")
    }

}

Be sure to use AppCompatActivity()