개발 공부/Android / / 2022. 9. 26. 23:59

[Android Kotlin]ViewBinding과 DataBinding 차이 & Databinding 적용하기

간단한 차이 정리

단순히 findViewById를 이용한 View 접근 번거로움(View 개수대로 코드 추가)으로 사용했던 ViewBinding을 좀 더 알아보다가 DataBinding에 대한 것도 다시 보게 되었다. 

 

둘의 차이라고 한다면 ViewBinding은 기능이 적은대신 DataBinding보다 빠르고 사용하기가 편하다

ViewBinding은 사용할 때 xml에 무언가 추가할 필요 없이 모듈에서 binding 설정만 하면 쉽게 사용할 수 있는 것과는 반면DataBinding을 사용하려면 xml 파일에 <layout>태그로 감싸야 하기 때문이었다.

그러나 ViewBinding은 양방향바인딩을 지원하지 않는다. 그리고 동적인 UI 콘텐츠를 생성할 수 없다. 

 

DataBinding이 ViewBinding이 하는 역할도 할 수는 있지만 DataBinding을 단순히 findViewById를 대체하기 위한 용도로 쓰는 경우 이때는 ViewBinding이 더 효율적이기 때문에 구글에서도 이럴 경우 ViewBinding 사용을 권장하고 있다.

 

이 둘이 가진 차이가 분명해서 적절하게 필요에 맞게 사용하면 좋을 것 같다. 

 

 

DataBinding 적용하기

1. gradle(Module) 추가

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

2. xml로 가서 <layout>태그로 감싸기 & <data> 태그 넣기

기본 틀

<?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=""
            type="" />
    </data>
    
   //뷰는 여기에 넣는다
   
</layout>

<data> 태그의 variable은 뷰와 데이터를 이어주는 역할을 한다. name은 변수와 같은 역할을 하고 type에는 연결하고 싶은 데이터가 있는 경로(Class)를 넣어준다.

적용 예 

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <data>
        <import type="androidx.core.content.ContextCompat"/>

        <variable
            name="activity"
            type="me.saeha.android.navermovie_project.MainActivity" />
    </data>

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

 

3.뷰와 데이터 연결하기 

TextView의 text에 객체를 사용하듯이 <data> 태그의 이름.데이터값을 @{} 넣어서 입력. Button을 눌러서 TextView의 값이 바뀌도록 하는 것을 해보자 

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <data>
        <import type="androidx.core.content.ContextCompat"/>

        <variable
            name="activity"
            type="me.saeha.android.navermovie_project.MainActivity" />
    </data>

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

        <TextView
            android:id="@+id/tv_test"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{activity.text}"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/btn_change"
            app:layout_constraintVertical_chainStyle="packed"/>

        <Button
            android:id="@+id/btn_change"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_test"
            app:layout_constraintBottom_toBottomOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

4. 뷰와 연결된 클래스로 binding 처리 및 데이터 값 선언 

아래 코드의 text가 위의 xml TextView의 text에 들어가 있는 activity.text이고 버튼을 누르면 TextView의 값이 TEST SUCCESS로 바뀐다.

class MainActivity : AppCompatActivity() {
    private lateinit var binding : ActivityMainBinding

    var text = "TEST"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
        binding.activity = this
        binding.btnChange.setOnClickListener {
            text ="TEST SUCCESS"
            binding.invalidateAll()
        }
    }
}
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유