| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- cs기초
- boj
- 백준
- 자바스크립트
- blender4.0
- 3D그래픽
- 카드뉴스
- 3d모델링
- CS
- 알고리즘
- 블렌더도넛
- csharp
- 단계별로 풀어보기
- 블렌더튜토리얼
- 단계별문제풀이
- Python
- Photoshop
- 포토샵
- 블렌더
- 파이썬
- 도넛튜토리얼
- c언어
- 비트연산
- leetcode
- blender
- 프로그래머스
- 코딩테스트
- AI
- level1
- 3d스터디
- Today
- Total
슬로우도파민
[AndroidStudio-Kotlin] View Binding 뷰 바인딩 본문
View에서 메서드를 호출하거나 속성에 액세스하기 전에, 먼저 Button 또는 TextView와 같은 View에 대한 참조를 찾아야 합니다.
안드로이드 프레임워크는 이를 위해 findViewById() 메서드를 제공합니다.
findViewById() 예제 코드
// Old way with findViewById()
val myButton: Button = findViewId(R.id.my_button)
myButton.text = "A Button"
View Binding
findViewById() 대신 View Binding을 통해 UI의 뷰에서 메서드를 훨씬 더 쉽고 빠르게 호출할 수 있습니다.
1. Gradle에서 View Binding 사용 설정
앱의 build.gradle 파일을 열고 android 섹션에서 다음 줄을 추가합니다.
buildFeatures {
viewBinding = true
}
'Gradle files have changed since last project sync' 라는 메시지가 뜨면 Sync Project with Gradle File 버튼을 클릭해서 싱크를 맞춰줍니다.
2. 결합 객체 초기화
MainActivity.kt 의 OnCreate() 함수 내에서 binding 객체를 초기화해줍니다.
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
코드 설명
lateinit var binding: ActivityMainBinding
activity_main.xml 레이아웃의 binding 객체를 초기화 합니다.
lateinit 키워드는 late init 즉, 늦은 초기화를 말합니다.
코틀린에서는 늦은 초기화를 하려면 선언 시 null값을 명시해줘야하는데
이 대신 lateinit라는 키워드를 사용하여 선언을 먼저 해두고
변수를 사용하기 이전에 초기화를 할 것이다 라고 명시해줍니다.
binding = ActivityMainBinding.inflate(layoutInflater)
여기서는 binding 객체를 초기화해줍니다. Binding 클래스 이름은 XML 파일의 이름을 카멜 표기법으로 변환하고 이름끝에 'Binding'을 추가하여 생성됩니다. 마찬가지로 각 뷰를 위한 참조는 밑줄을 삭제하고 이름을 카멜표기법으로 변환하여 생성됩니다. 예를 들어 activity_main.xml은 ActivityMainBinding 이 되고 binding.textView로 @id/text_view에 액세스 할 수 있습니다.
setContentView(binding.root)
activity의 contentView를 설정합니다. 레이아웃 리소스 ID인 R.layout.activity_main을 전달하는 대신, 앱의 뷰 계층 구조 루트인 binding.root 를 지정합니다.
결과
// Better way with view binding
val myButton: Button = binding.myButton
myButton.text = "A button"
// Best way with view binding and no extra variable
binding.myButton.text = "A button"'개발기록 > 개발스터디' 카테고리의 다른 글
| [Unreal] Actor 클래스 (0) | 2024.01.31 |
|---|---|
| [안드로이드-코틀린] Adding a RecyclerView to your app (0) | 2021.07.16 |
| 안드로이드 스튜디오 TIPS (0) | 2021.07.12 |
| 안드로이드 스튜디오 개발환경설정 (0) | 2021.07.05 |
| [iOS] 뷰의 상태 변화 메서드 (0) | 2021.03.24 |
