Skip to content

Instantly share code, notes, and snippets.

@abdulhafizramadan-ittp
Last active May 30, 2022 16:22
Show Gist options
  • Select an option

  • Save abdulhafizramadan-ittp/3755f197c35453e4ae6816646b150eb2 to your computer and use it in GitHub Desktop.

Select an option

Save abdulhafizramadan-ittp/3755f197c35453e4ae6816646b150eb2 to your computer and use it in GitHub Desktop.
Android | Launch Intent Gallery
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.galleryButton.setOnClickListener { startGallery() }
}
private val launcherIntentGallery =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val selectedImg = result.data?.data as Uri
binding.previewImageView.setImageURI(selectedImg)
}
}
private fun startGallery() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
val intentChooser = Intent.createChooser(intent, "Choose a picture")
launcherIntentGallery.launch(intentChooser)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment