기록

[Android/Kotlin] 데이터바인딩 (DataBinding) 본문

[Study]/Android

[Android/Kotlin] 데이터바인딩 (DataBinding)

Dannnnnn 2022. 6. 2. 01:19
반응형

안드로이드는 원하는 View를 찾을 때 까지 런타임에 Root에서 시작하여 View 계층을 탐색한다.

때문에 앱의 View 계층 구조가 복잡한 경우, findViewById()는 비용이 많이 들고 앱의 속도를 느려지게 한다.

다행히 이를 개선하기 위한 방법이 있고, 이것이 데이터 바인딩이다.

 

View에서 데이터를 보이기 위해 string resources를 사용하고 Activity/Fragment에 데이터를 선언한다.

데이터 바인딩은 View가 데이터에 대해 미리 알고있게 하여 이를 더욱 효율적이게 해준다.

 

데이터 바인딩 기술은 전체 앱에서 사용할 수 있는 각 View에 대한 참조가 포함된 바인딩 개체를 만드는 것이다.

앱에 대한 바인딩 개체를 만든 후에는 View 계층을 이동하거나 데이터를 탐색할 필요 없이 바인딩 개체를 통해 View 및 기타 데이터에 접근할 수 있다.

 

Data binding has the following benefits:

  • Code is shorter, easier to read, and easier to maintain than code that uses findViewById().
  • Data and views are clearly separated. This benefit of data binding becomes increasingly important later in this course.
  • The Android system only traverses the view hierarchy once to get each view, and it happens during app startup, not at runtime when the user is interacting with the app.
  • You get type safety for accessing views. (Type safety means that the compiler validates types while compiling, and it throws an error if you try to assign the wrong type to a variable.)

 

데이터 바인딩 라이브러리를 사용하여 XML에서 직접 데이터에 접근해 findViewById()와 관련한 비효율적인 호출을 제거해보자.

 

Step 1: Enable data binding

Gradle 파일에서 데이터 바인딩을 사용할 수 있도록 설정해준다.

It's not enabled by default. This is because data binding increases compile time and may affect app startup time.

 

- Open the build.gradle (Module: app) file.

- Inside the android section, before the closing brace, add a buildFeatures section and set dataBinding to true.

buildFeatures {
    dataBinding true
}

Step 2: Change layout file to be usable with data binding

데이터 바인딩으로 작업하려면 XML 레이아웃을 <layout> 태그로 감싸야 한다. 이렇게 하면 root 클래스는 더 이상 View 그룹이 아니라 View 그룹 및 View를 포함하는 레이아웃이 된다. 이를 통해 바인딩 개체는 레이아웃과 뷰에 대해 알 수 있다.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto">
   <LinearLayout ... >
   ...
   </LinearLayout>
</layout>

Step 3: Create a binding object

Fragment 또는 Activity에 바인딩 개체에 대한 참조를 추가하여 View에 액세스할 수 있도록 한다.

onCreate() 이전 최상단에 바인딩 개체에 대한 변수를 만든다.
바인딩 타입인 ActivityMainBinding 클래스는 컴파일러에 의해 생성되며, 이름은 레이아웃 파일 이름 + Binding에서 파생된다.

private lateinit var binding: ActivityMainBinding

다음으로 기본으로 제공되는 setContentView() 함수를 수정한다.

선언한 바인딩 개체를 초기화하고, DataBindingUtil 클래스의 setContentView() 함수를 사용하여 현재 Activty 또는 Fragment와 이에 매칭되는 레이아웃을 연결한다.

binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

Step 4: Use the binding object to replace all calls to findViewById()

이제 findViewById()에 대한 모든 호출을 바인딩 개체를 이용한 View에 대한 참조로 바꿀 수 있다.

바인딩 오브젝트가 생성되면, 컴파일러는 바인딩 개체가 참조하게 할 View의 이름을 레이아웃의 View ID로부터 카멜 케이스로 생성한다.

binding.doneButton.setOnClickListener {
   addNickname(it)
}

 

데이터 바인딩이 후드에서 어떻게 이뤄지는지 궁금하다면 공식 문서를 참조할 수 있다.

반응형