我正在尝试在我的数据绑定(bind)中使用 null 合并运算符。我有一个复合可绘制对象,我需要显示三个可绘制对象图标之一,具体取决于变量是 null、true 还是 false。
XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.view.View" />
<variable
name="dataModel"
type="com.my.app.MyDataModel" />
</data>
<TextView
android:id="@id/mCompoundDrawable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@{(dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified }"
android:focusable="true"
android:gravity="center_vertical"
android:scrollHorizontally="false"
android:text="@{dataModel.text}" />
</layout>
数据模型
public class MyDataModel
{
public String text;
public Boolean isSelected;
public MyDataModel(String text, Boolean isSelected)
{
this.text = text;
this.isSelected = isSelected;
}
}
我通过调用调用它:
MyDataModel dataModel = new MyDataModel(text, null);
binding.setDataModel(dataModel);
我以为
android:drawableRight="@{(dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified }
实际上等同于:
android:drawableRight="@{dataModel.isSelected != null? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified }
但是,我在运行时遇到以下异常:
java.lang.NullPointerException:尝试在空对象引用上调用虚方法“boolean java.lang.Boolean.booleanValue()”
我想知道如何克服这个错误。谢谢!
最佳答案
(1) (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified
不一样
(2) dataModel.isSelected != null ? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified
在第一个表达式中,您会收到错误,因为运算符 ?:
在 null
指针上隐式调用了 dataModel.isSelected.booleanValue()
.
无论如何,我相信在这种情况下您无法使用空合并运算符,所以我只使用第二个表达式。
关于Android 数据绑定(bind)空合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777936/