Closed cheewr85 closed 2 years ago
2.4에서 이야기 한 부분의 핵심 포인트는 결국 findViewById()
사용이 생각보다 비용이 꽤 많이 드는 작업이고 간단한 앱이라면 상관이 없지만 기본적으로 서비스 수준의 앱을 쓰는데 있어서 findViewById()
를 자주 사용한다면 그만큼 성능 저하가 일어날 수 있기 때문에 Data Binding을 활용하는 것을 권장했음
근데 이번 챕터에서 보기전에 먼저 View Binding을 먼저 접하고 사용하고 있었는데 View Binding과 Data Binding의 차이점을 한 번 짚고 넘어가는게 좋을 것 같음
View Binding 역시 findViewById()
를 통해서 직접 id를 적고 타입을 정하는 작업을 하지 않고 직접 각 XML 레이아웃 파일에 있는 binding 클래스를 만듬
그래서 해당 xml의 id에 대해서 직접적으로 참조해서 가져올 수 있음, 그래서 불러오고 처리하는 면에 있어서는 Data Binding과 유사하게 진행이 됨 무슨말이냐면 Binding Class 이름을 정해지는데 규칙이 유사하게 진행이 됨
아래와 같이 활용해서 Activity에서 처리할 수 있음
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
그래서 어떻게 보면 지금까지 View Binding에 대해서 findViewById
의 불편함에 의해서 이를 해소하고자 사용했는데 단순히 이것을 교체해서 쓸 용도면 이렇게 쓰는것이 나은것이 맞음, Data Binding과 비교했을 때 간단하게 사용되고 생성되는것도 더 빠르게 되는 것은 맞기 때문에
결과적으로 View Binding의 경우 한편으론 findViewById()
의 타입 안정성, 널 안정성의 문제를 해결해주고 속도 측면에서 개선하는데 있어서 쓰기 유용하다고 볼 수 있음 추후에 이 부분이 ViewModel과 결합되어서 유용하게 쓰일 수 있음
ViewModel은 UI 컨트롤러(Activity, Fragment등)에서 데이터 관리시 생명주기에 따라 값이 사라지고(핸드폰을 회전만 해도 사라짐), 그러자니 이걸 saveInstanceState를 통해서 관리하기에는 한계가 있기 때문에 온전히 UI 관련 데이터만을 관리해주는 것임, 이는 추후에 진행하면서 그 때 상세하게 다룰 예정 + LiveData도 있는데 이 역시 마찬가지로 추후에 자세히 다뤄볼 예정
Data Binding은 2.4 에서 배웠다시피 어쨌든 취지 자체도 findViewById()
를 개선하는 관점은 View Binding과 유사할 수 있음
하지만 Data Binding은 살짝 과정이 더 있고 xml에 코드를 집어 넣어서 데이터와 뷰를 연결하는 작업을 레이아웃에서 처리할 수 있음
비교를 하자면 findViewById()
와 View Binding에서는 문장을 넣는데 아래와 같이 썼다면
// findViewById 쓸때는 이렇게 했었고
textView.text = "안녕"
// 뷰 바인딩 쓸때는 이렇게 했다. binding.textView.text = "안녕"
- Data Binding의 경우, xml에 코드를 집어넣어서 해결할 수 있음
```kotlin
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.name}" />
여기서 View Binding과 조금 다른 부분은 Data Binding은 좀 더 포괄적인 범주임 View Binding의 역할도 할 수 있을뿐더러 동ㅈ거 UI 컨텐츠 선언, 양방향 데이터 결합도 지원이 가능함
그렇다고 이 말이 무조건 Data Binding만 사용하라는 것이 아님 findViewById()
의 대체로 View Binding이 오히려 Data Binding보다 성능이 좋기 때문에 상황에 맞게 골라서 사용하면 됨
그리고 Data Binding을 적용하는 과정을 2.4에서 했던 기초적인 방법과 동일함 xml에서 <layout>
태그를 아래와 같이 설정해주고
<layout>
<LinearLayout ... >
...
</LinearLayout>
</layout>
이렇게 쓰면 View Binding과 유사하게 Binding 객체를 통해서 XML의 요소들을 불러와서 처리할 수 있음
private lateinit var binding: ActivityMainBinding
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>
이러면 단순히 xml상에서 데이터 연결 뿐 아니라 특정 클래스에서 위의 UserProfile 인스턴스를 만들어서 해당 클래스의 인수의 변수를 할당한다면 그 할당된 변수 역시 갱신해서 user.firstName
으로 쓸 수가 있음
여기서 양방향 바인딩이 가능하다는 것은 ViewModel을 활용, 해당 값을 다이렉트로 표시해서 UI에 업데이트가 되는 방식으로 같이 묶여서 활용이 가능한 것을 의미함
물론 View Binding을 활용해도 LiveData와 ViewModel을 활용하면 마치 양방향 바인딩처럼 감지를 갱신하고 처리할 수 있지만 위의 설명은 어디까지나 ViewModel과 LiveData를 배제한 것이고 아무리 쓰더라도 Data Binding은 직접적으로 xml 상에서 <data>
태그와 그 태그를 바탕으로 직접 연결해서 바뀌는 것을 감지하고 처리하는 것이기 때문에 엄연히 다름
이를 제대로 활용하고 응용하기 위해선 아키텍처와 ViewModel, LiveData를 응용하는 것이 좋고 그게 아니라면 단순하게 findViewById()
를 개선하는 정도로 볼 수 있음(이 말이 떨어진다는 것이 아닌 ViewModel, LiveData 활용시 더더욱 잘 쓸 수 있다는 것임)
[질문]
2.4에서 Data Binding에 적용과 어떻게 쓰는지 그리고 어떤 원리로 쓰이는지 알게 되었는데 이를 View Binding과 비교해서 그 차이를 정리해보면?