Notice
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 클래스
- 2022 플러터 안드로이드 스튜디오
- 안드로이드 유닛 테스트
- rxjava disposable
- 플러터 설치 2022
- 안드로이드 os 구조
- 서비스 vs 쓰레드
- rxjava cold observable
- 큐 자바 코드
- 자바 다형성
- 스택 큐 차이
- 멤버변수
- Rxjava Observable
- 안드로이드 라이선스 종류
- 안드로이드 유닛 테스트 예시
- 안드로이드 유닛테스트란
- 스택 자바 코드
- jvm 작동 원리
- android retrofit login
- 객체
- 안드로이드 레트로핏 사용법
- ANR이란
- jvm이란
- android ar 개발
- 서비스 쓰레드 차이
- rxjava hot observable
- 안드로이드 레트로핏 crud
- ar vr 차이
- 안드로이드 라이선스
- 2022 플러터 설치
Archives
- Today
- Total
나만을 위한 블로그
[Android] 코틀린으로 registerForActivityResult() 써서 갤러리에서 이미지 가져오기 본문
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 체크를 좀 더 깔끔하게 할 수 있다.
이외의 코드들은 딱히 특별할 게 없는 코드기 때문에 설명은 생략한다.
반응형
'Android' 카테고리의 다른 글
[Android] MVP vs MVVM (0) | 2022.12.05 |
---|---|
[Android] EventBus란? EventBus 사용법 (0) | 2022.11.21 |
[Android] 날짜 변환 시 사용하는 enum과 확장 함수 모음 (0) | 2022.11.10 |
[Android] 코틀린으로 안드로이드 KG이니시스 결제 연동하는 법 [2022 Ver] (0) | 2022.11.09 |
[Android] 이미지 캐시 (0) | 2022.10.03 |
Comments