数据绑定通常通过检查 NullPointerException 并分配默认值(例如 null)来避免 NullPointerException,即使
item
本身在示例中为 null。
但是对项目属性进行 null 检查的基本示例:
android:text='@{item.title != null ? user.title : ""}'
或者使用“空合并运算符”。空合并运算符 (
??
) 如果左操作数不为空,则选择左操作数;如果为空,则选择右操作数。
android:text='@{item.title ?? ""}'
请注意,
title
或 getTitle
并不重要。
数据绑定不需要检查null值,它会被处理 通过绑定类。
如果您需要检查 null 用于其他目的(例如设置默认值),那么您可以这样使用。
android:text='@{item.gender != null ? item.gender : @string/male}'
或
android:text='@{item.gender ?? @string/male}'
上面两个例子都是一样的。这里
@string/male
为默认值,当 item.gender
为 null
时。
我尝试过这样的事情。
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="android.text.TextUtils"/>
<variable
name="mOrder"
type="com.test.app.models.Order" />
</data>
<TextView
android:id="@+id/mLblSource"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text='@{TextUtils.isEmpty(mOrder.order_id) ? "- -" : mOrder.order_id}'
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</layout>
android:visibility="@{UserDetails == null ? View.INVISIBLE : View.VISIBLE}"