【问题标题】:Android Data Binding Null Coalescing OperatorAndroid 数据绑定空合并运算符
【发布时间】:2017-04-08 06:11:21
【问题描述】:

我正在尝试在我的数据绑定中使用 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: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

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

【问题讨论】:

    标签: android android-databinding compound-drawables


    【解决方案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

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

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

    【讨论】:

    • 第二个表达式也会导致空指针异常
    猜你喜欢
    • 2011-02-20
    • 2012-09-19
    • 2018-10-18
    • 2013-09-13
    • 2015-03-27
    • 2023-03-23
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多