-
[Android] [인스타그램 클론 코딩] 갤러리 접근 허용 & 사진 이미지 뷰에 등록 (registerForActivityResult() 사용)안드로이드 2024. 4. 3. 15:34
✏️ TIL(Today I Learned)
맨 왼쪽의 파란색 + 버튼이 겹쳐진 이미지 뷰를 클릭하면, 갤러리 접근 허용 권한을 선택할 수 있게 했다.
사용자가 허용한다면, 갤러리를 열어 선택된 사진이 이미지 뷰에 등록되도록 했다.
권한을 얻기 위해, AndroidManifest.xml에 아래 코드를 추가한다.
// AndroidManifest.xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
그다음 Activity에서 이미지뷰 클릭 시, 갤러리 접근 권한을 확인한다.
registerForActivityResult()를 사용하여, 권한이 허용되어 있으면 갤러리를 열어 선택한 사진을 이미지뷰에 등록한다.
권한이 없으면, 권한을 허용 여부를 묻도록 했다.
class MainActivity : AppCompatActivity() { private lateinit var ivCamera: ImageView private var imageUri: Uri? = null // 권한에 따라 갤러리 열기 private val requestPermissionLauncher: ActivityResultLauncher<String> = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> if (isGranted) { openGallery() } } // 선택한 사진 이미지뷰에 등록하기 private val pickImageLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { val data: Intent? = result.data data?.data?.let { imageUri = it ivCamera.setImageURI(imageUri) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //프로필 사진 이미지뷰 클릭 시 ivCamera = findViewById(R.id.Iv_camera) ivCamera.setOnClickListener { // 갤러리 접근 권한 확인 if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED ) { openGallery() } else { requestPermissionLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE) } } } private fun openGallery() { val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI) pickImageLauncher.launch(gallery) } }
'안드로이드' 카테고리의 다른 글
[Android] MVVM 패턴 회원가입 유효성 검사 (0) 2024.04.09 [Android] 인스타그램 클론 코딩 팀 프로젝트 KPT 회고록 (0) 2024.04.08 [Android] Dark theme 구현 (다크 모드 전용 리소스 정의) (0) 2024.04.03 [Android] [Kotlin] addTextChangedListener와 setOnFocusChangeListener의 차이 (EditText 입력 변화 이벤트 처리) (0) 2024.04.02 [Android] [인스타그램 클론 코딩] 스토리 UI 만들기 (원형 이미지 뷰: CircleImageView) (0) 2024.04.02