Android

[Android] 코틀린으로 registerForActivityResult() 써서 갤러리에서 이미지 가져오기

참깨빵위에참깨빵_ 2022. 11. 10. 20:05
728x90
반응형

예전에 자바로 같은 내용의 포스팅을 작성한 적이 있다.

 

https://onlyfor-me-blog.tistory.com/342

 

[Android] startActivityForResult()를 대체할 registerForActivityResult()로 이미지 가져오는 법

몇 년 동안 써왔던 startActivityForResult(), onActivityResult()가 deprecated되었다. 그 대신 새로운 api인 registerForActivityResult()가 나왔다고 한다. 그래서 이미지를 가져오는 코드가 어떻게 바뀌었는지 확인해

onlyfor-me-blog.tistory.com

 

이 글의 소스코드를 코틀린으로 바꾸면 어떻게 되는지 정리한다.

자세한 내용은 생략하고 XML부터 작성한다. 이미지뷰 하나만 있는 건 똑같지만 데이터 바인딩을 사용할 것이기 때문에 전체 구조만 조금 다르다.

 

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".other.TestActivity">

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHeight_percent=".2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias=".15"
            app:layout_constraintWidth_percent=".4" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

 

그리고 코틀린 파일을 아래처럼 만든다.

 

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.bumptech.glide.Glide
import com.example.kotlinprac.databinding.ActivityTestBinding
import kotlinx.android.synthetic.main.activity_test.*

class TestActivity : AppCompatActivity() {

    private lateinit var launcher: ActivityResultLauncher<Intent>

    private val binding: ActivityTestBinding by lazy {
        ActivityTestBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        init()
    }

    private fun init() {
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val intent = checkNotNull(result.data)
                val imageUri = intent.data
//                imageview.setImageURI(imageUri)
                Glide.with(this)
                    .load(imageUri)
                    .into(imageview)
            }
        }

        imageview.setOnClickListener {
            val intent = Intent().also { intent ->
                intent.type = "image/"
                intent.action = Intent.ACTION_GET_CONTENT
            }
            launcher.launch(intent)
        }
    }

}

 

실행하면 자바 포스팅과 마찬가지로 이미지뷰에 setImageURI()로 갤러리에서 가져온 이미지를 넣든 Glide로 이미지를 넣든 잘 들어가는 걸 볼 수 있다.

다른 점이라면 코틀린은 checkNotNull()을 제공한다. 이것은 매개변수로 넣은 값이 null이면 IllegalStateException을 리턴하고 null이 아니면 받아야 할 값을 리턴하는 함수로 null 체크를 좀 더 깔끔하게 할 수 있다.

이외의 코드들은 딱히 특별할 게 없는 코드기 때문에 설명은 생략한다.

반응형