问题描述
无法理解...仅当变量字段不为null时,如何设置视图的某些属性?
例如
Cannot understand... How to set some property of view only if variable field isn't null?
For example
<?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
.仅当属性不为null时,才能设置属性吗?
P.S.对不起,英语.
Some field of Item can be null and I won't call methods of layout views unnecessarily. And I won't get NullPointerException
. How can I set property only if it isn't null?
P.S. Sorry for English.
推荐答案
好的数据绑定通常通过检查NullPointerException来避免NullPointerException并分配默认值(例如null),即使您的示例中item
本身为null.
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.
但有一个用于对项目属性进行null检查的基本示例:
But a basic example for null checks for the item's properties:
android:text='@{item.title != null ? user.title : ""}'
或使用空合并运算符".空合并运算符(??
)如果不为null,则选择左操作数;如果为null,则选择右操作数.
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 ?? ""}'
请注意,title
或getTitle
无关紧要.
这篇关于数据绑定:如果不为null,则设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!