4

我正在尝试在我的数据绑定中使用空合并运算符。我有一个复合可绘制对象,我需要显示三个可绘制图标之一,具体取决于变量是空、真还是假。

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

我想知道如何克服这个错误。谢谢!

4

1 回答 1

1

(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

在第一个表达式中,您会收到错误,因为运算符隐式?:调用指针。dataModel.isSelected.booleanValue()null

无论如何,我相信在这种情况下你无法使用空合并运算符,所以我只使用第二个表达式。

于 2016-11-24T04:24:51.637 回答