简体   繁体   中英

Android Data Binding Null Coalescing Operator

I'm trying to use the null coalescing operator in my data binding. I have a compound drawable that I need to show one of three drawable icons, depending on if the variable is null, true, or false.

The 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>

The Data Model

public class MyDataModel
{
    public String text;
    public Boolean isSelected;

    public MyDataModel(String text, Boolean isSelected)
    {
        this.text = text;
        this.isSelected = isSelected;
    }
}

I invoke this by calling:

    MyDataModel dataModel = new MyDataModel(text, null);
    binding.setDataModel(dataModel);

I thought that

android:drawableRight="@{(dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified } 

is effectively the same as:

android:drawableRight="@{dataModel.isSelected != null? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified }

However, I get the following exception at runtime:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

I'm wondering how I can overcome this error. Thanks!

(1) (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified

is not the same as

(2) dataModel.isSelected != null ? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified dataModel.isSelected != null ? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified

In the first expression, you get the error because operator ?: calls dataModel.isSelected.booleanValue() implicitly on a null pointer.

Anyway, I believe there's no way you can use the null coalescing operator in the case, so I would just use the second expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM