Hyeyeon blog

[Android] 갤러리에서 사진 가져오기 - ActivityResultLauncher, Intent 본문

개발/Android

[Android] 갤러리에서 사진 가져오기 - ActivityResultLauncher, Intent

Hyeyeon.P 2022. 3. 2. 14:22
반응형

Intent를 이용한 방법

  1. 갤러리 호출

val PICK_IMAGE_REQUEST = 1001
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, PICK_IMAGE_REQUEST)

  2. 선택한 사진 불러오기

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
	super.onActivityResult(requestCode, resultCode, data)
    
	if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
		val uri : Uri? = data?.data
		if(uri != null) {
			imageView.setImageURI(uri)
		}
	}
}

 

ActivityResultLauncher를 이용한 방법

var launcher = 
	registerForActivityResult<String, Uri>(ActivityResultContracts.GetContent()) { uri -> setImage(uri) }
launcher.launch("image/*")

 

관련 글

>> [Android] onActivityResult를 대체하는 ActivityResult API

728x90
Comments