Android Databinding Safety Null
2021. 11. 17. 09:42ㆍAndroid/Information
Databinding을 통해 데이터를 뿌려줄 때 뿌릴려는 객체 안 데이터가 NULL이라면 그대로 NULL로 표시되는 경우가 있다.
(일반적인 경우에는 나오지 않으나 데이터 2개를 +연산자를 통해 합친다던지 할 때 발생하는 것으로 확인된다.)
이 때 이 NULL을 컨트롤하는 방법이다.
1
|
android:text='@{vm.testObj.strText1 + " " + vm.testObj.strText2}'
|
cs |
위와 같이 되어 있을 때(vm은 View Model) testObj 내 strText1, 2가 null로 되어 있다면 'null null' 로 표시된다.
이 현상을 고치는 방법은 2개가 있다.
1. 엘비스 연산자(Elvis Operation)
: Kotlin에서 엘비스 연산자를 쓸 때 '?:' 이렇게 쓴 경험이 있을거다.
XML 상에서도 엘비스 연산자를 쓸 수 있는데 사용방법은 아래와 같다.
1
|
android:text='@{(vm.testObj.strText1 ?? "") + " " + (vm.testObj.strText2 ?? "")}'
|
cs |
'??' 을 이용해 컨트롤 하면 된다.
2. 삼항 연산자
: 일반적인 삼항 연산자를 생각하면 된다.
'a == null ? true : false'
1
|
android:text='@{(vm.testObj.strText1 != null ? vm.testObj.strText1 : "") + " " + (vm.testObj.strText2 != null ? vm.testObj.strText2 : "")}'
|
cs |
출처)
https://stackoverflow.com/questions/36227194/data-binding-set-property-if-it-isnt-null
'Android > Information' 카테고리의 다른 글
Android <android:Text> Tag Not Working (0) | 2021.11.12 |
---|---|
Android ↔ Typescript 함수 공유 방법 (2) (0) | 2021.10.27 |
Android ↔ Typescript 함수 공유 방법 (1) (0) | 2021.10.27 |