Data binding: set property if it isn't null

后端 未结 2 1623
无人共我
无人共我 2021-02-03 18:42

Cannot understand... How to set some property of view only if variable field isn\'t null?
For example




        
相关标签:
2条回答
  • 2021-02-03 18:56

    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.

    But a basic example for null checks for the item's properties:

    android:text='@{item.title != null ? user.title : ""}'
    

    Or use the "Null Coalescing Operator". The null coalescing operator (??) chooses the left operand if it is not null or the right if it is null.

    android:text='@{item.title ?? ""}'
    

    Note that title or getTitle doesn't matter.

    0 讨论(0)
  • 2021-02-03 18:58

    Data binding does not need to check for null value, it will be handled by binding class.

    If you need to check null for other purpose (like setting default value) then you can use like this.

    android:text='@{item.gender != null ? item.gender : @string/male}'
    

    or

    android:text='@{item.gender ?? @string/male}'
    

    Both above examples are same. Here @string/male is default value, when item.gender is null.

    0 讨论(0)
提交回复
热议问题