코틀린 [Kotlin/Android] DataBinding

황제낙엽 2022.11.13 06:51 조회 수 : 3498

1. DataBinding 이란

  - xml에 있는 데이터들을 코드단으로 손쉽게 바인딩 시켜준다.

  - 2019년 Google I/O에서 설명한바 있다. DataBinding, Navigation, Room, View Model .. 등등

 

2. 장점

  - findViewId 를 쓰면, 런타임에 뷰 계층 구조를 찾아야하며, 딥 뷰 계층 같은 경우는 사용자 앱 속도를 늦출 수 있다. 이것을 해결하기 위해서 DataBinding 기술과 패턴이 나왔다.

  - 컴파일 타임에 레이아웃 또는 프래그먼트들을 연결할 수 있게 만들어주어, DataBinding 으로 오버 헤드 없이 사용할 수 있는 장점이 있다.

 

3. 개발 환경

  - Android Studio 3.6 이상

 

4. Gradle 설정 (Module: app)

android {
    ...
    dataBinding {
        enabled = true
    }

    buildFeatures{
        dataBinding = true
        viewBinding = true
    }
}

 

5. xml 설정 (layout > activity_main.xml)

  명심해야할것은 꼭 최상위 <layout> </layout> 으로  감싸야한다.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp" />

        <Button
            android:id="@+id/roll_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/roll" />
    </LinearLayout>

</layout>

 

6. kotlin (MainActivity.kt)

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.rollButton.text = "Let's Roll!!"
    }
    
}

  ActivityMainBinding 을 하고, import 된것을 보면, [패키지명].[프로젝트명].databinding.ActivityMainBinding 으로 될 것이다.

  import [패키지명].[프로젝트명].databinding.ActivityMainBinding 코드로 임포트 해야 한다

  그리고 다음과 같이 접근할 수 있다

lateinit var binding: ActivityMainBinding

binding = ActivityMainBinding.inflate(layoutInflater)

 

  이름이 정의된 규칙은 아래와 같다.

 

  1) xml 파일 명이 activity_main.xml 이면 ActivityMainBinding 이다.

  2) xml 파일 명이 main_activity.xml 이면 MainActivityBinding 이다.

 

7. 결과

  - setContextView 가 없어지고, DataBindingUtil 으로 setContextView 하는것을 볼 수 있다.

  - binding 객체로 findViewId 없이, xml에 선언된 +id/roll_button가 binding.rollButton 으로 접근 가능해졌다.

 

 

 

※ 클래스 파일에서 binding code가 계속해서 에러를 뱉어낸다면 Clean Project, Rebuild Project 를 수행하도록 한다

번호 제목 글쓴이 날짜 조회 수
128 PC를 위한 최고의 안드로이드 에뮬레이터 황제낙엽 2023.01.18 3132
127 [Jetpack Compose UI / 상추님] GDG Jetpack compose 코드랩 수료 후기 (feat. 굿즈) 황제낙엽 2022.12.24 2370
126 [Jetpack Compose UI / kyj1991719] compose - Compose 이해 황제낙엽 2022.12.24 4025
125 [Jetpack Compose UI / 꾸준] Compose 가 뭔데...? 황제낙엽 2022.12.24 4035
124 [Jetpack Compose UI / IIVIKI] Compose 학습과 분석 황제낙엽 2022.12.24 4050
123 [Jetpack Compose UI] 스터디 시작하기 황제낙엽 2022.12.24 4001
122 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 바텀네비게이션 뷰, 네비게이션 AAC file 황제낙엽 2022.12.22 3882
121 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 뷰바인딩 file 황제낙엽 2022.12.22 3850
120 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 라이브데이터 뷰모델 file 황제낙엽 2022.12.21 3826
119 [대왕놀] ImageButton in Compose (IconButton) 황제낙엽 2022.12.20 4105
118 [대왕놀] compose instrumentation test tutorial 황제낙엽 2022.12.20 3985
117 [대왕놀] Switch in Compose 황제낙엽 2022.12.20 4106
116 [대왕놀] EditText in Compose (TextField) 황제낙엽 2022.12.20 4021
115 [대왕놀] margin in Compose 황제낙엽 2022.12.20 4105
114 [대왕놀] modifier in compose 황제낙엽 2022.12.20 4180
113 [대왕놀] Button in Compose file 황제낙엽 2022.12.20 4224
112 [대왕놀] TextView in Compose (Text) 황제낙엽 2022.12.20 4083
111 [대왕놀] ImageView in Compose (Image) 황제낙엽 2022.12.20 4017
110 [대왕놀] LinearLayout in Compose (Row, Column) 황제낙엽 2022.12.20 4113
109 [대왕놀] Introduction to Jetpack compose 황제낙엽 2022.12.20 3964