Android Jetpack Architecture/DataBinding
DataBinding 표현식 정리
hik14
2020. 8. 7. 15:52
속성 = @{ }
지원되지 않는 기능
- this
- super
- new
- 명시적 제네릭 호출
Null 병합 연산자 (?? )
- 사용법
3항 연산자를 통해 이름이 있으면 이름을 텍스트로 지정하고 없으면 string 리소스를 지정한다.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{currentUser.name != null ? currentUser.name : @string/no_name}"
/>
이걸 Null 병합 연산자를 통해 다음처럼 줄여 쓸 수 있다.
피연산자(왼쪽)?? 피연산자(오른쪽) ---> 왼쪽의 값이 날이 아니면 그대로 지정 날이면 오른쪽의 값을 지정
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{currentUser.name ?? @string/no_name}"
/>
null 포인터 예외 방지
생성된 데이터 결합 코드는 자동으로 null 값을 확인하고 null 포인터 예외를 방지합니다. 예를 들어 @{user.name} 표현식에서 user가 null이면 user.name에 null이 기본값으로 할당됩니다. age의 유형이 int인 user.age를 참조하면 데이터 결합은 0의 기본값을 사용합니다.
Collection 클래스 사용하기
- 사용법
아래와 같이 사용할 컬렉션 및 데이터를 import 태그를 이용하여 지정한다.
그리고 바인딩 변수를 생성한다. HashMap <type, type>에서 < 문자는 이스케이프 처리를 해야 한다.
<data>
<import type="java.util.HashMap"/>
<import type="com.professionalandroid.apps.databinding.User"/>
<variable
name="userMap"
type="HashMap<Integer, User>"
/>
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{userMap.get(1).name}"
/>
리소스 사용하기
@{ @string/name }과 같은 형태로 사용될 수 있다.