cheewr85 / Kotlin-Android-Basic

CodeLab 기반으로 기본기 다시보기
3 stars 0 forks source link

Data Binding vs View Binding #12

Closed cheewr85 closed 2 years ago

cheewr85 commented 2 years ago

[질문]

2.4에서 Data Binding에 적용과 어떻게 쓰는지 그리고 어떤 원리로 쓰이는지 알게 되었는데 이를 View Binding과 비교해서 그 차이를 정리해보면?

cheewr85 commented 2 years ago
cheewr85 commented 2 years ago

View Binding

ViewModel은 UI 컨트롤러(Activity, Fragment등)에서 데이터 관리시 생명주기에 따라 값이 사라지고(핸드폰을 회전만 해도 사라짐), 그러자니 이걸 saveInstanceState를 통해서 관리하기에는 한계가 있기 때문에 온전히 UI 관련 데이터만을 관리해주는 것임, 이는 추후에 진행하면서 그 때 상세하게 다룰 예정 + LiveData도 있는데 이 역시 마찬가지로 추후에 자세히 다뤄볼 예정

cheewr85 commented 2 years ago

Data Binding

// 뷰 바인딩 쓸때는 이렇게 했다. binding.textView.text = "안녕"


- Data Binding의 경우, xml에 코드를 집어넣어서 해결할 수 있음
```kotlin
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@{user.name}" />

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


- 이렇게 활용하는 건 어떻게 보면 View Binding과 유사하지만 다른점이 있다면 Data Binding은 Data class는 바로 View에 이용할 수 있다는 점이 다름
- 무슨 말이냐면 type에 연결하고 싶은 데이터가 있다면 해당 경로를 `<data>` 태그에 적어주고 이때 `name`에 사용할 이름을 정하고 해당 클래스에 있는 데이터 변수를 아래와 같이 직접 쓸 수 있는 것을 말함

```xml
<?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="user"
            type="com.example.selfstudy_kotlin.UserProfile" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{user.lastName}" />
    </LinearLayout>
</layout>
cheewr85 commented 2 years ago

참고자료

View Binding과 Data Binding 예제 View Binding Data Binding ViewModel LiveData

Data Binding 양방향 binding View Binding과 Data Binding 차이

공식 문서

View Binding Data Binding