我正在尝试在我的数据绑定中使用空合并运算符。我有一个复合可绘制对象,我需要显示三个可绘制图标之一,具体取决于变量是空、真还是假。
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: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
我想知道如何克服这个错误。谢谢!