Android 数据绑定(bind)空合并运算符

标签 android android-databinding compound-drawables

我正在尝试在我的数据绑定(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/

相关文章:

java - Android 6 上的布局问题。充气机问题?在 Android 5 及更早版本上运行良好

android - 错误 : Cannot find ActivitySplashBinding

android - Sony Xperia S (LT26i) 似乎没有显示复合绘图

android - 在事件上向 EditText 显示复合可绘制对象

android - 如何使用不同的屏幕分辨率

android - intentService 是否会导致 Activity 并发问题

android - 如何使用数据绑定(bind)初始化 Recycler View 适配器上的点击监听器?

android - 如何缩小按钮上的可绘制对象?

android - 纹理的最大尺寸是多少(Andengine)

android - 使用数据绑定(bind)设置千位分隔符格式