[Android] DataBinding

강승구·2022년 12월 28일
0

DataBinding은 UI 요소와 데이터를 프로그램적 방식으로 연결하지 않고 선언적 형식으로 결합할 수 있도록 도와주는 Jetpack 라이브러리의 한 기능이다.

프로그램적 방식과 선언적 방식

프로그램적 방식

TextView에 문자열을 넣기 위해 코틀린 코드상에서 값을 집어넣는다.

// findViewById
val textView = findViewById<TextView>(R.id.textView)
textView.text = "hello"

// ViewBinding
binding.textView.text = "hello"

선언적 방식

코틀린 코드에는 로직만을 위한 코드를 만기고 뷰와 관련된 작업은 레이아웃 파일(XML)에 정의한다.

<TextView
	android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@{viewmodel.userName}" />

즉 dataBinding은 데이터와 뷰를 연결하는 작업을 레이아웃(XML)파일에서 처리하는 기술을 말한다. DataBinding을 사용하면 기존에 View 레벨에서 코드로 작성하던 것을 대부분 XML에서 처리할 수 있기 때문에 View의 코드가 깔끔해지고 유지보수가 용이해진다는 장점이 있다.


DataBinding vs ViewBinding

DataBinding은 ViewBinding의 역할도 수행할 뿐만 아니라 추가로 동적 UI콘텐츠 선언과 양방향 data binding도 지원한다.
ViewBinding이 DataBinding보다 성능이 좋고 용량이 절약되는 장점이 있기 때문에 단순히 findViewById를 대체하기 위해 Binidng기법을 사용한다면 ViewBinding을 사용하는 것이 좋다.


장단점

장점

  • 액티비티에서 뷰에 접근하는 보일러 플레이트 코드를 작성하지 않아도 된다.
  • 뷰모델에 데이터나 함수 등을 정의해 두고 속성을 지정만 하면 되기 때문에 재사용이 쉽다.
  • 양방향 바인딩을 활용하면 뷰 변경에 따라 데이터도 자동으로 갱신되고, Live Data와 함께 사용하면 data가 변할 때마다 view가 자동으로 갱신되기 때문에 작성할 코드가 훨씬 줄어들고 뷰와 데이터를 서로의 변경에 상관없이 완벽하게 일치시킬 수 있다.

단점

  • xml은 기본적으로 디버깅이 안되기 때문에, 데이터가 제대로 넘어가지 않는 경우 이유를 확인하기 어렵다.
  • 클래스 파일이 많이 생기고, 이에 따라 빌드 속도가 느려지며 앱 용량도 증가한다.

사용법

1. build.gradle 추가

  • Android Studio 4.0 이상
android{
	...
    buildFeatures {
    	dataBidning = true
        }
}
  • Android Studio 3.6 ~ 4.0
android{
	...
    dataBinding {
    	enabled true
        }
}

2. layout 형식 변경

DataBinding을 사용하기 위해서는 layout의 구조를 변경해주어야 한다.
layout을 루트 태그로 시작하도록 수정해준다.

<?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=".MainActivity">

		...

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

3. 변수 설정

profile
강승구

0개의 댓글