无法理解...仅当变量字段不为空时如何设置视图的某些属性?
例如
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="item"
type="com.test.app.Item" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:src="@{item.getDrawable()}"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginEnd="16dp"
android:layout_marginLeft="72dp"
android:layout_marginRight="16dp"
android:layout_marginStart="72dp"
android:layout_toLeftOf="@id/action"
android:layout_toStartOf="@id/action"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="@color/black_87"
android:textSize="16sp"
android:text="@{item.getTitle()}"/>
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web|email"
android:linksClickable="false"
android:singleLine="true"
android:textColor="@color/black_54"
android:textSize="14sp"
android:text="@{item.getSubtitle()}"/>
</LinearLayout>
</RelativeLayout>
</layout>
Item 的某些字段可以为 null,并且我不会不必要地调用布局视图的方法。我不会得到NullPointerException
。仅当属性不为空时,如何设置属性?
附:对不起英语。
数据绑定通常通过检查 NullPointerException 并分配默认值(例如 null)来避免 NullPointerException,即使item
在你的例子中它本身是空的。
但是 null 检查项目属性的基本示例:
android:text='@{item.title != null ? user.title : ""}'
或者使用“空合并运算符”。空合并运算符 (??
) 如果左操作数不为空,则选择左操作数;如果为空,则选择右操作数。
android:text='@{item.title ?? ""}'
注意title
or getTitle
没关系。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)