https://developer.android.com/topic/libraries/data-binding
레이아웃의 UI 구성요소를 앱의 데이터 소스와 결합할 수 있는 지원 라이브러리다.
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
<TextView
android:text="@{viewmodel.userName}" />
데이터 바인딩을 간단하게 살펴볼때 위와 같이 편리함을 자랑하고 있는데, 그럼 model이 null일경우는? binding해야하는 데이터가 null일 경우 xml은 npe가 안날까?
스택오버플로우에서는 기본적으로 피해간다고 한다.
Well data binding avoids NullPointerException in general by checking for it and assigns the default value (null for example) even if item itself is null in your example.
Data binding does not need to check for null value, it will be handled by binding class.
생성되는 데이터 바인딩 코드는 자동으로 null 검사하여 null 포인터 예외를 피한다.
예를 들면
user가 null 인 경우
user.name은 기본값(null)
user.age는 기본값(0) (여기서 age는 int)
이 때문에 확인해보고자 binding class를 확인해보았으나, super 안쪽이 private 라서 볼수는 없지만 그렇다고 한다.
공식에서도 그렇다할 말이 없으니 정 불안하다면 연산자로 처리할 수 있다.
android:text='@{item.title != null ? user.title : ""}'
or
android:text='@{item.title ?? ""}'