DataBinding

구교석·2024년 5월 14일
post-thumbnail

DataBinding이란?

데이터 바인딩(Data Binding)은 소프트웨어 개발에서 UI와 비즈니스 로직 또는 데이터 모델을 느슨하게 결합하는 기술입니다. 이를 통해 UI 요소와 데이터 모델 사이의 동적인 연결을 수행할 수 있습니다.

안드로이드에서는 Android Data Binding 라이브러리를 통해 데이터 바인딩을 구현할 수 있습니다. 이 라이브러리는 XML 레이아웃 파일에서 직접 UI 요소와 데이터 모델을 바인딩할 수 있는 기능을 제공합니다.

지난번에 알아봤던 View Binding과 비슷하니 View Binding을 구현해 본 사람은 쉽게 구현할 수 있다.

많이 쓰는 패턴인 MVVM 패턴을 사용할 때 LiveData와 함께 많이 쓰인다.

DataBinding 사용을 위한 요소가 많지 않으니 바로 알아보도록 하자.

DataBinding 구현

먼저 샘플용으로 만들어 볼 앱은 메인 화면의 TextView에 "Hello World!"가 표시되고 Button을 Click하게 되면 TextView에 "Hello Databinding!"이 출력 됩니다.

graddle에서 아래의 세팅의 추가 합니다.

android {
    ...
   dataBinding {    
 	   enabled true
   }
}

그 후 데이터바인딩을 설정할 액티비티 뷰의 xml로 이동해서 소스를 열어봅니다.
최상단 루트를 layout 태그로 감싸줍니다.

기본 xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout     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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/hello_text_view"
        android:text="Hello!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
  
    <Button
        android:id="@+id/btn_change"
        android:text="Text Change!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/hello_text_view"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

여기에서 최상단의 ConstraintLayout을 layout 아래로 둡니다.
그리고 data, variable을 추가합니다.

<?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">
  
    <data>
      <variable
         name="main"
         type="com.joel.jojo.MainActivity"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/hello_text_view"
            android:text="Hello!"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
      
        <Button
            android:id="@+id/btn_change"
            android:text="Text Change!"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/hello_text_view"
            app:layout_constraintBottom_toBottomOf="parent"/>

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

MainActivity

class MainActivity : AppCompatActivity() {
    // xml 파일명이 카멜케이스로 클래스가 자동생성 됩니다.
    private lateinit var binding: ActivityMainBinding

    var text = "Hello!"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // binding 세팅
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        // 현재 binding시킨 xml의 variable name
        binding.main = this
        // binding 버튼 클릭 이벤트
        binding.btnChange.setOnClickListener {
            text = "Hello Binding!"
            // Data가 변동될 경우 binding된 View들에 Data 변화를 알려줌
            binding.invalidateAll()
        }
    }
}

DataBinding 장점

간편한 UI 업데이트

데이터 바인딩을 사용하면 UI 요소를 직접 업데이트할 필요 없이 데이터 모델의 변경 사항이 자동으로 UI에 반영됩니다.

코드 및 XML 분리

데이터 바인딩을 사용하면 UI 레이아웃과 비즈니스 로직이 서로 완전히 분리됩니다. XML 파일에서 데이터 모델을 직접 참조하여 UI를 정의할 수 있습니다.

참고사이트


코틀린 데이터 바인딩(Data binding)
안드로이드 데이터바인딩(dataBinding) 사용

profile
끊임없이 노력하는 개발자

0개의 댓글